[ { "from": "human", "value": "Can brain cells move? By movement I mean long distance migration (preferably within the brain only)." }, { "from": "gpt", "value": "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.\nHowever, after sifting through various publications, the answer to the question is actually remarkably simple: Yes, brain cells migrate.\nIn 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).\nNeuronal 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).\nPost-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).\nNot 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)." } ]
[ { "from": "human", "value": "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.\nIt 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!\nSo I figure there have to be good arguments why large portions of the processor market use CISC architectures. What are they? " }, { "from": "gpt", "value": "There is a general historical trend.\nIn 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. \nIn 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.\nMIPS is the ultimate RISC architecture, which is why it's taught so often.\nThe 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.\nIn 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.\nOn 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.\nOn 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.\nSo 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." } ]
[ { "from": "human", "value": "View tabular file such as CSV from command line, having horizontal and vertical scrolling would be great." }, { "from": "gpt", "value": "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). \n\nHere 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:\n```$ csvgrep -e iso-8859-1 -c 1 -m \"de\" worldcitiespop | csvgrep -c 5 -r \"\\d+\"\n | csvsort -r -c 5 -l | csvcut -c 1,2,4,6 | head -n 11 | csvlook\n-----------------------------------------------------\n| line_number | Country | AccentCity | Population |\n-----------------------------------------------------\n| 1 | de | Berlin | 3398362 |\n| 2 | de | Hamburg | 1733846 |\n| 3 | de | Munich | 1246133 |\n| 4 | de | Cologne | 968823 |\n| 5 | de | Frankfurt | 648034 |\n| 6 | de | Dortmund | 594255 |\n| 7 | de | Stuttgart | 591688 |\n| 8 | de | Düsseldorf | 577139 |\n| 9 | de | Essen | 576914 |\n| 10 | de | Bremen | 546429 |\n-----------------------------------------------------\n```\n\nCsvkit is platform independent because it is written in Python. " } ]
[ { "from": "human", "value": "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.\nAlso, exact hydrogen wavefunctions decay exponentially, so the motivation for STOs.\nI 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.\nMy 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$." }, { "from": "gpt", "value": "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:\n$$\n(-\\frac{1}{2}\\nabla^2 + V(\\mathbf{r}))\\psi(\\mathbf{r}) = \\epsilon\\psi(\\mathbf{r}), \\epsilon < 0\n$$\nAt spatial points that are very far away from the nucleus, $V(\\mathbf{r})\\approx 0$, so that the asymptotic solution is given by\n$$\n-\\frac{1}{2}\\nabla^2\\psi(\\mathbf{r}) = \\epsilon\\psi(\\mathbf{r}), \\epsilon < 0\n$$\nThis differential equation has basic solutions of the form\n$$\n\\psi(\\mathbf{r}) = Ce^{-\\sqrt{-2\\epsilon}\\mathbf{k}\\cdot\\mathbf{r}}\n$$\nfor 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.\nOf 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)\n$$\n\\psi(\\mathbf{r}) = Ce^{-\\sqrt{2I}\\mathbf{k}\\cdot\\mathbf{r}}\n$$\nAlthough 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." } ]
[ { "from": "human", "value": "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.\nI think ```git reset``` is close to ```hg revert```, but it seems there are differences. Please include detailed explanations about:\n\n* the options ```--hard```, ```--soft``` and ```--merge```;\n* the strange notation you use with ```HEAD``` such as ```HEAD^``` and ```HEAD~1```;\n* concrete use cases and work flows;\n* consequences on the working copy, the ```HEAD``` and your global stress level." }, { "from": "gpt", "value": "Remember that in ```git``` you have:\n\n* the ```HEAD``` pointer, which tells you what commit you're working on\n* the working tree, which represents the state of the files on your system\n* the staging area (also called the index), which \"stages\" changes so that they can later be committed together\n\n\n> Please include detailed explanations about:\n ```--hard```, ```--soft``` and ```--merge```;\n\nIn increasing order of dangerous-ness:\n\n* ```--soft``` moves ```HEAD``` but doesn't touch the staging area or the working tree.\n* ```--mixed``` moves ```HEAD``` and updates the staging area, but not the working tree.\n* ```--merge``` moves ```HEAD```, resets the staging area, and tries to move all the changes in your working tree into the new working tree.\n* ```--hard``` moves ```HEAD``` and adjusts your staging area and working tree to the new ```HEAD```, throwing away everything.\n\n\n> concrete use cases and workflows;\n\n\n* 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.\n\n```\n# git reset --soft example\ntouch foo // Add a file, make some changes.\ngit add foo //\ngit commit -m \"bad commit message\" // Commit... D'oh, that was a mistake!\ngit reset --soft HEAD^ // Go back one commit and fix things.\ngit commit -m \"good commit\" // There, now it's right.\n```\n--\n\n* 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.\n* Use ```--merge``` when you want to move to a new spot but incorporate the changes you already have into that the working tree.\n* Use ```--hard``` to wipe everything out and start a fresh slate at the new commit." } ]
[ { "from": "human", "value": "I am looking to use Java to get the MD5 checksum of a file.\nHow is it done?" }, { "from": "gpt", "value": "The API offers:\n\n* A unified user-friendly API for all hash functions\n* Seedable 32- and 128-bit implementations of murmur3\n* md5(), sha1(), sha256(), sha512() adapters, change only one line of code to switch between these, and murmur.\n* goodFastHash(int bits), for when you don't care what algorithm you use\n* General utilities for HashCode instances, like combineOrdered / combineUnordered\n\nRead the User Guide (IO Explained, Hashing Explained). \nFor your use-case ```Files.hash()``` computes and returns the digest value for a file.\nFor example a sha-1 digest calculation (change SHA-1 to MD5 to get MD5 digest)\n```HashCode hc = Files.asByteSource(file).hash(Hashing.sha1());\n\"SHA-1: \" + hc.toString();\n```\nNote 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. \nFor 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).\nNote that crc32 has a higher collision rate than the others. \nWhat part of Files.hash as stated above does not cover Files.hash ?" } ]
[ { "from": "human", "value": "What are the primary objections Democrats have to a border wall?" }, { "from": "gpt", "value": "It's not clear to me that Democrats are opposed to border-wall construction (your one source suggests they are fine with border walls/fences where necessary), so much as they opposed to some of the plans for full-border walls that have been put forth so far.\nRecently, in response to reports that the spending bill would include funding for a border wall, 5 Democratic senators released a letter voicing concerns over the cost, the effectiveness, and the legal issues of constructing it.\n\nWe are also concerned with reports that there may be an effort to include funding for a very expensive new wall along the southern border with Mexico and a “deportation force.” According to non-partisan experts, the proposed new border wall could cost as much as $25 million per mile and raises considerable issues that have not been resolved by the Congress or the Department of Homeland Security. First, many experts believe that such a border wall will not work. Second, there is real concern that the Administration, put simply, has no plan to build the border wall. For example, the Administration has not detailed how to 1) use eminent domain and other procedures to acquire land from private landowners and Native American tribes, 2) design the wall, 3) locate the wall, 4) construct the wall, and 5) require Mexico to pay for the wall given the President’s clear and repeated promises that he would force Mexico to do so. Finally, there are objections to the construction of a wall from Democratic and Republican members of Congress that represent border states. Given these and other concerns, we believe it would be inappropriate to insist on the inclusion of such funding in a must-pass appropriations bill that is needed for the Republican majority in control of the Congress to avert a government shutdown so early in President Trump’s Administration.\n[...]\nSenator Charles Schumer\nSenator Richard Durbin\nSenator Patty Murray\nSenator Debbie Stabenow\nSenator Patrick Leahy\n\nBased on this letter, it appears their main objections to a full border wall are currently the cost-benefit ratio and the legal issues of taking land from Americans to build it on; objections that may not be unique to Democrats." } ]
[ { "from": "human", "value": "I'm converting a video to GIF file with ```ffmpeg```:\n```ffmpeg \\\n -i input.flv \\\n -ss 00:00:00.000 \\\n -pix_fmt rgb24 \\\n -r 10 \\\n -s 320x240 \\\n -t 00:00:10.000 \\\n output.gif\n```\nIt works great, but output gif file has a very low quality.\nAny ideas how can I improve quality of converted gif?" }, { "from": "gpt", "value": "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:\n```ffmpeg -i input.flv -vf scale=320:-1 -r 10 -f image2pipe -vcodec ppm - | convert -delay 10 -loop 0 - output.gif\n```\nThe ```-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.\nTo optimize the result without saving a file, you can pipe the output from ```convert``` to a second ```convert``` command:\n```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\n```\nThe ```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.\nRemember that during this whole process everything is in memory so you may need sufficient memory if the images are quite large." } ]
[ { "from": "human", "value": "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?" }, { "from": "gpt", "value": "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\nYour tor client, once it has created a circuit, will send that hostname and port to the exit node in its RELAY_BEGIN cell.\nThe 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.\nTor, 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.\nNo UDP packets are actually ever routed from the client.\nThere's also a proposal to add more full featured DNS support to Tor. So far it hasn't been implemented.\n\nTor Protocol Specification references\n\n* 6.2. Opening streams and transferring data\n* 6.4. Remote hostname lookup\n* Proposal 219 - Support for full DNS and DNSSEC resolution in Tor\n" } ]
[ { "from": "human", "value": "Why does this throw ```NullPointerException```\n```public static void main(String[] args) throws Exception {\n Boolean b = true ? returnsNull() : false; // NPE on this line.\n System.out.println(b);\n}\npublic static Boolean returnsNull() {\n return null;\n}\n```\nwhile this doesn't\n```public static void main(String[] args) throws Exception {\n Boolean b = true ? null : false;\n System.out.println(b); // null\n}\n```\n?\nThe 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?" }, { "from": "gpt", "value": "The difference is that the explicit type of the ```returnsNull()``` method affects the static typing of the expressions at compile time:\n```E1: `true ? returnsNull() : false` - boolean (auto-unboxing 2nd operand to boolean)\nE2: `true ? null : false` - Boolean (autoboxing of 3rd operand to Boolean)\n```\nSee Java Language Specification, section 15.25 Conditional Operator ? :\n\n* For E1, the types of the 2nd and 3rd operands are ```Boolean``` and ```boolean``` respectively, so this clause applies:\n\n 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.\n\nSince 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.\n* 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:\n\n 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) (§\n\n\n* S1 == `````` (see §4.1)\n* S2 == ```boolean```\n* T1 == box(S1) == `````` (see last item in list of boxing conversions in §5.1.7)\n* T2 == box(S2) == `Boolean\n* lub(T1, T2) == ```Boolean```\n\nSo 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.\n\n\nThis question needs a similar type analysis:\nJava conditional operator ?: result type" } ]
[ { "from": "human", "value": "How do DOS games like DOOM benefit from a PCI graphics card?" }, { "from": "gpt", "value": "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.\nPCI 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.)\nA 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.\nYour 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).\nFor 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." } ]
[ { "from": "human", "value": "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?" }, { "from": "gpt", "value": "```open``` and ```start``` are command-interpreter things for Mac OS/X and Windows respectively, to do this.\nTo call them from Python, you can either use ```subprocess``` module or ```os.system()```. \nHere are considerations on which package to use:\n\n* You can call them via ```os.system```, which works, but...\nEscaping: ```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\n\n* MacOS/X: ```os.system(\"open \" + shlex.quote(filename))```\n* Windows: ```os.system(\"start \" + filename)``` where properly speaking ```filename``` should be escaped, too.\n\n* You can also call them via ```subprocess``` module, but...\nFor Python 2.7 and newer, simply use\n```subprocess.check_call(['open', filename])\n```\nIn Python 3.5+ you can equivalently use the slightly more complex but also somewhat more versatile\n```['open', filename], check=True)\n```\nIf you need to be compatible all the way back to Python 2.4, you can use `````` and implement your own error checking:\n```try:\n retcode =\"open \" + filename, shell=True)\n if retcode < 0:\n print >>sys.stderr, \"Child was terminated by signal\", -retcode\n else:\n print >>sys.stderr, \"Child returned\", retcode\nexcept OSError, e:\n print >>sys.stderr, \"Execution failed:\", e\n```\nNow, what are the advantages of using ```subprocess```?\n\n* 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 `````` gives us little additional protection.\n* 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).\n* 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.\n\nTo 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.\nA marked disadvantage is that the Windows ```start``` command requires you to pass in ```shell=True``` which negates most of the benefits of using ```subprocess```.\n" } ]
[ { "from": "human", "value": "Why does PRC devalue its currency on purpose, but Turkey is worried about the devaluation of its currency?" }, { "from": "gpt", "value": "Trade surplus/deficit\nDevaluing 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.\nIn 2016, Turkey imported goods worth US $186 billion and exported goods worth US $156 billion. That means they had a trade deficit of 19%.\nHowever, 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%.\nWhich is why China wants to devalue their currency while Turkey does not.\nDebt management\nAnother 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. \nChina 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%.\nWhich is why reducing debt through causing inflation seems more attractive to China than to Turkey.\nForeign investor relations\nSo 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." } ]
[ { "from": "human", "value": "Is it worth patenting an algorithm if I don't have the money to defend against infringements?" }, { "from": "gpt", "value": "This is a great question, with no one right answer.\nThe strength of a patent comes from the ability to enforce it. If the patent owner cannot enforce it for whatever reason (such as a lack of funding), the patent is effectively toothless.\nBut your competitors will likely not know that. They may therefore be dissuaded from infringing simply by the existence of a patent and the assumption that you would sue. Such a chilling effect on competition may be valuable to you.\nIn addition, if there is infringement, you may be able to get a licensing agreement without the need for litigation. This can be a very lucrative business model, and so may justify the cost of patenting.\nAnd if litigation seems likely, there is a nascent field of litigation funding. While your funders will take quite a great deal of the damages, you may at least get something out of the end of it.\nFinally, even if you can't sue, someone else could. You might therefore get quite some value from selling it off at some point. There are a number of tech businesses where most of their value comes from their IP portfolio.\nOn the whole therefore it depends how you see yourself proceeding. If you're unsure, it may pay to err on the side of patenting: once you disclose or use your invention publicly, you're generally barred from patenting it later (but for a short grace period in some countries), whereas it's easy to abandon a patent (or application) later down the track if you wish." } ]
[ { "from": "human", "value": "\"I have a ```String[]``` with values like so:\n```public static final String[] VALUES = new String[] {\"\"AB\"\",\"\"BC\"\",\"\"CD\"\",\"\"AE\"\"};\n```\nGiven ```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?" }, { "from": "gpt", "value": "Four Different Ways to Check If an Array Contains a Value:\n\n* Using ```List```:\n```public static boolean useList(String[] arr, String targetValue) {\n return Arrays.asList(arr).contains(targetValue);\n}\n```\n* Using ```Set```:\n```public static boolean useSet(String[] arr, String targetValue) {\n Set set = new HashSet(Arrays.asList(arr));\n return set.contains(targetValue);\n}\n```\n* Using a simple loop:\n```public static boolean useLoop(String[] arr, String targetValue) {\n for (String s: arr) {\n if (s.equals(targetValue))\n return true;\n }\n return false;\n}\n```\n* Using ```Arrays.binarySearch()```:\nThe 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.\n```public static boolean binarySearch(String[] arr, String targetValue) {\n return Arrays.binarySearch(arr, targetValue) >= 0;\n}\n```\n\nQuick Example:\n```String testValue=\"test\";\nString newValueNotInList=\"newValue\";\nString[] valueArray = { \"this\", \"is\", \"java\" , \"test\" };\nArrays.asList(valueArray).contains(testValue); // returns true\nArrays.asList(valueArray).contains(newValueNotInList); // returns false\n```" } ]
[ { "from": "human", "value": "Does Java casting introduce overhead? Or the compiler just resolves everything and there is no cost at run time?\nIs this a general things, or there are different cases?" }, { "from": "gpt", "value": "There are 2 types of casting in Java:\n\nImplicit casting, when you cast from a type to a wider type, which is done automatically and there is no overhead:\n```String s = \"Cast\";\nObject o = s; // implicit casting\n```\nExplicit casting, when you go from a wider type to a more narrow one. For this case, you must explicitly use casting like that:\n```Object o = someObject;\nString s = (String) o; // explicit casting\n```\nIn this second case, there is overhead in runtime, because the two types must be checked and in case that casting is not feasible, JVM must throw a ClassCastException.\n\nTaken from JavaWorld: The cost of casting\n\n> Casting is used to convert between types -- between reference types in particular, for the type of casting operation in which we're interested here. Upcast operations (also called widening conversions in the Java Language Specification) convert a subclass reference to an ancestor class reference. This casting operation is normally automatic, since it's always safe and can be implemented directly by the compiler. Downcast operations (also called narrowing conversions in the Java Language Specification) convert an ancestor class reference to a subclass reference. This casting operation creates execution overhead, since Java requires that the cast be checked at runtime to make sure that it's valid. If the referenced object is not an instance of either the target type for the cast or a subclass of that type, the attempted cast is not permitted and must throw a java.lang.ClassCastException.\n" } ]
[ { "from": "human", "value": "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\"?" }, { "from": "gpt", "value": "There are two classes that lives in different assemblies and different namespaces.\n\n* WinForms: use following namespace declaration, make sure ```Main``` is marked with ```[STAThread]``` attribute:\n```using System.Windows.Forms;\n```\n* WPF: use following namespace declaration\n```using System.Windows;\n```\n* 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\n```using System.Windows.Forms;\n```\n\nTo copy an exact string (literal in this case):\n```Clipboard.SetText(\"Hello, clipboard\");\n```\nTo copy the contents of a textbox either use TextBox.Copy() or get text first and then set clipboard value:\n```Clipboard.SetText(txtClipboard.Text);\n```\nSee here for an example.\nOr... Official MSDN documentation or Here for WPF.\n\nRemarks:\n\n* 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.\n* 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\n* This question/answer covers regular .NET, for .NET Core see - .Net Core - copy to clipboard?\n" } ]
[ { "from": "human", "value": "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.\n```\\usepackage{draftwatermark}\n\\SetWatermarkText{DRAFT}\n\\SetWatermarkScale{1}\n```" }, { "from": "gpt", "value": "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:\nFirst, with the unstarred variant (material on the background, so a figure will be placed on top of it):\n```\\documentclass{article}\n\\usepackage[printwatermark]{xwatermark}\n\\usepackage{xcolor}\n\\usepackage{graphicx}\n\\usepackage{lipsum}\n\\newwatermark[allpages,color=red!50,angle=45,scale=3,xpos=0,ypos=0]{DRAFT}\n\\begin{document}\n\\lipsum[1-2]\n\\begin{figure}[!ht]\n\\centering\n\\includegraphics[width=3cm]{example-image-a}\n\\end{figure}\n\\lipsum[1-2]\n\\end{document}\n```\n\nAnd now, with the starred variant (material on the foreground, so it will appear on top of figures):\n```\\documentclass{article}\n\\usepackage[printwatermark]{xwatermark}\n\\usepackage{xcolor}\n\\usepackage{graphicx}\n\\usepackage{lipsum}\n\\newwatermark*[allpages,color=red!50,angle=45,scale=3,xpos=0,ypos=0]{DRAFT}\n\\begin{document}\n\\lipsum[1-2]\n\\begin{figure}[!ht]\n\\centering\n\\includegraphics[width=3cm]{example-image-a}\n\\end{figure}\n\\lipsum[1-2]\n\\end{document}\n```\n" } ]
[ { "from": "human", "value": "Understanding the Rails Authenticity Token" }, { "from": "gpt", "value": "What is CSRF?\nThe Authenticity Token is a countermeasure to Cross-Site Request Forgery (CSRF). What is CSRF, you ask?\nIt's a way that an attacker can potentially hijack sessions without even knowing session tokens. \nScenario:\n\n* Visit your bank's site, log in.\n* Then visit the attacker's site (e.g. sponsored ad from an untrusted organization).\n* Attacker's page includes form with same fields as the bank's \"Transfer Funds\" form.\n* Attacker knows your account info, and has pre-filled form fields to transfer money from your account to attacker's account.\n* Attacker's page includes Javascript that submits form to your bank.\n* When form gets submitted, browser includes your cookies for the bank site, including the session token.\n* Bank transfers money to attacker's account.\n* The form can be in an iframe that is invisible, so you never know the attack occurred. \n* This is called Cross-Site Request Forgery (CSRF). \n\nCSRF solution:\n\n* Server can mark forms that came from the server itself\n* Every form must contain an additional authentication token as a hidden field.\n* Token must be unpredictable (attacker can't guess it).\n* Server provides valid token in forms in its pages.\n* Server checks token when form posted, rejects forms without proper token. \n* Example token: session identifier encrypted with server secret key.\n* Rails automatically generates such tokens: see the authenticity_token input field in every form. \n" } ]
[ { "from": "human", "value": "Why is FIFA against adding instant replay to the game?" }, { "from": "gpt", "value": "There are a few fundamental considerations:\n\n* Uncertainty is a part of the game. The referee and linesmen are the arbiters of the action. Instant replay would limit their authority.\n* Football is global. Many places do not have access to the technology necessary to implement instant replay.\n* Football is a fast-paced game with few opportunities for stoppage. Instant replay would unnecessarily slow the pace.\n\nIn 2008, FiFA President Sepp Blatter said:\n\n \"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.\"\n\nBlatter 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.\nAlthough 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.\nFIFA may choose to implement further changes to approved goal-line technology and referee rules when it meets again after the World Cup." } ]
[ { "from": "human", "value": "If we should encrypt the message rather than the method of transfer, why do we care about wifi security? Is this just security theatre?" }, { "from": "gpt", "value": "Network encryption protects against different set of threats than application layer encryption like TLS.\nIn 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.\nTLS 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.\nThe 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.\nNetwork 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." } ]
[ { "from": "human", "value": "Applying filter in scipy.signal: Use lfilter or filtfilt?" }, { "from": "gpt", "value": "\n* ```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.\n* ```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.\n\nAn 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:\n\n```from __future__ import division, print_function\nimport numpy as np\nfrom numpy.random import randn\nfrom numpy.fft import rfft\nfrom scipy import signal\nimport matplotlib.pyplot as plt\nb, a = signal.butter(4, 0.03, analog=False)\n# Show that frequency response is the same\nimpulse = np.zeros(1000)\nimpulse[500] = 1\n# Applies filter forward and backward in time\nimp_ff = signal.filtfilt(b, a, impulse)\n# Applies filter forward in time twice (for same frequency response)\nimp_lf = signal.lfilter(b, a, signal.lfilter(b, a, impulse))\nplt.subplot(2, 2, 1)\nplt.semilogx(20*np.log10(np.abs(rfft(imp_lf))))\nplt.ylim(-100, 20)\nplt.grid(True, which='both')\nplt.title('lfilter')\nplt.subplot(2, 2, 2)\nplt.semilogx(20*np.log10(np.abs(rfft(imp_ff))))\nplt.ylim(-100, 20)\nplt.grid(True, which='both')\nplt.title('filtfilt')\nsig = np.cumsum(randn(800)) # Brownian noise\nsig_ff = signal.filtfilt(b, a, sig)\nsig_lf = signal.lfilter(b, a, signal.lfilter(b, a, sig))\nplt.subplot(2, 1, 2)\nplt.plot(sig, color='silver', label='Original')\nplt.plot(sig_ff, color='#3465a4', label='filtfilt')\nplt.plot(sig_lf, color='#cc0000', label='lfilter')\nplt.grid(True, which='both')\nplt.legend(loc=\"best\")\n```" } ]
[ { "from": "human", "value": "What do different people in the department expect from a postdoc?\nBy different people I mean the advisor, graduate students and PhD students.\nI 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.\nThe above are my thoughts. My question is divided into the following sub-parts:\n\n* What would you as a professor expect from your postdoc? \n* What preparation one must do to rise to the expected level? \n* Is the preparation merely restricted to having sound academic record and experience?" }, { "from": "gpt", "value": "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.\nA postdoc needs to do the following:\n\n* Build a publication record. This will involve both what you are paid to do and your own line of research.\n* Get involved with supervising students. Help with the PhDs in the lab, and get involved in supervising masters students.\n* Get involved with obtaining funding. This can either be by helping your employer or (ideally) obtaining your own funding. \n* Build an international reputation.\n* Start collaborating with external parties.\n* Gain some teaching experience. This is absolutely crucial if you want a faculty position.\n* 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.\n* 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.\n\nBe 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)." } ]
[ { "from": "human", "value": "Can someone explain to me what the ```contentInset``` property in a ```UIScrollView``` instance is used for? And maybe provide an example?" }, { "from": "gpt", "value": "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:\n``` _|←_cW_→_|_↓_\n | |\n---------------\n |content| ↑\n ↑ |content|\ncH |content|\n ↓ |content| contentInset.bottom\n |content| ↓\n---------------\n |content|\n-------------↑-\n```\nThat's what you get when you do it, but the usefulness of it only shows when you scroll:\n``` _|←_cW_→_|_↓_\n |content| ← content is still visible\n---------------\n |content| ↑\n ↑ |content|\ncH |content|\n ↓ |content| contentInset.bottom\n |content| ↓\n---------------\n _|_______|___\n ↑\n```\nThat 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\"\nTo 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." } ]
[ { "from": "human", "value": "How is arc defined in TikZ?" }, { "from": "gpt", "value": "```\\draw (x,y) arc (start:stop:radius);``` draws an arc\n\n* with radius ```radius```\n* starts from ```(x,y)```\n* with center ```(x-r*cos(start), y-r*sin(start))``` and\n* ends at ```(x-r*cos(start)+r*cos(stop), y-r*sin(start)+r*sin(stop))```.\n\nFor example,\n``` \\draw[red] (0,0) arc (30:60:3);\n```\ndraws an arc\n\n* of radius ```3```\n* starting from ```(0,0)```\n* with center ```(0-3*cos(30),0-3*sin(30))``` and\n* ending at ```(0-3*cos(30)+3*cos(60),0-3*sin(30)+3*sin(60))```.\n\n```\\draw[blue] (0,0) -- ++(30+180:3) -- +(60:3);\n```\ndraw a blue line to the arc to make a complete sector.\n\nMinimal Working Example\n```\\documentclass[tikz,border=12pt]{standalone}\n\\begin{document}\n\\foreach \\start/\\stop in {30/60,45/90,135/180,0/180,45/315}\n{\n \\begin{tikzpicture}\n \\draw[lightgray,ultra thin] (-6,-6) grid (6,6);\n \\draw[red] (0,0) arc (\\start:\\stop:3);\n \\draw[blue] (0,0) -- ++(\\start+180:3) -- +(\\stop:3);\n \\node[anchor=north] at (0,6) {$(\\start:\\stop:3)$};\n \\end{tikzpicture}\n}\n\\end{document}\n```\n\n\n\n" } ]
[ { "from": "human", "value": "How to connect mysql workbench to running mysql inside docker?" }, { "from": "gpt", "value": "By default after deployment MySQL has following connection restrictions:\n```mysql> select host, user from mysql.user;\n+-----------+---------------+\n| host | user |\n+-----------+---------------+\n| localhost | healthchecker |\n| localhost | mysql.session |\n| localhost | mysql.sys |\n| localhost | root |\n+-----------+---------------+\n4 rows in set (0.00 sec)\n```\nApparently, for the security purposes you will not be able to connect to it outside of the docker image.\nIf you need to change that to allow root to connect from any host (say, for development purposes), do:\n\n* Start your mysql image with all port mappings required:\n```docker run -p 3306:3306 --name=mysql57 -d mysql/mysql-server:5.7```\n\nor, if the complete port mapping is required:\n```docker run -p 3306:3306 -p 33060:33060 --name=mysql57 -d mysql/mysql-server:5.7\n```\n\n* If this is the fresh installation - grab the default password:\n```docker logs mysql57 2>&1 | grep GENERATED```\n* Connect using ```mysql``` client directly to the mysqld in docker:\n```docker exec -it mysql57 mysql -uroot -p```\n* If this is the fresh installation you will be asked to change the password using ```ALTER USER``` command. Do it.\n* Run SQL:\n```update mysql.user set host = '%' where user='root';```\n* Quit the ```mysql``` client.\n* Restart the container:\n```docker restart mysql57```\n\nNow you will be able to connect from MySQL Workbench to\n```host: ``\nport: `3306`\n```\nAfter all the changes the query will show:\n```select host, user from mysql.user;\n+-----------+---------------+\n| host | user |\n+-----------+---------------+\n| % | root |\n| localhost | healthchecker |\n| localhost | mysql.session |\n| localhost | mysql.sys |\n+-----------+---------------+\n```" } ]
[ { "from": "human", "value": "Can meat spoil outside the fridge if it's baked into bread as a filling?" }, { "from": "gpt", "value": "There are two differences between your buns and a tin can.\nFirst, 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.\nSecond, 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." } ]
[ { "from": "human", "value": "I'm wondering how the XML Schema specification handles these cases:\n```\n```\nNo maxOccurs given -> Is this the cardinality [1..1]?\n```\n```\nI suppose this is simply invalid?\n```\n```\nIs this the cardinality [0..2] or [1..2]?\nIs there an \"official\" definition on how the XML Schema spec handles these cases?" }, { "from": "gpt", "value": "New, expanded answer to an old, commonly asked question...\nDefault Values\n\n* Occurrence constraints ```minOccurs``` and ```maxOccurs``` default to ```1```.\n\n\nCommon Cases Explained\n```\n```\nmeans ```A``` is required and must appear exactly once.\n\n```\n```\nmeans ```A``` is optional and may appear at most once.\n\n``` \n```\nmeans ```A``` is required and may repeat an unlimited number of times.\n\n``` \n```\nmeans ```A``` is optional and may repeat an unlimited number of times.\n\nSee Also\n\n* W3C XML Schema Part 0: Primer\n\n In general, an element is required to appear when the value of\n minOccurs is 1 or more. The maximum number of times an element may\n appear is determined by the value of a maxOccurs attribute in its\n declaration. This value may be a positive integer such as 41, or the\n term unbounded to indicate there is no maximum number of occurrences.\n The default value for both the minOccurs and the maxOccurs attributes\n is 1. Thus, when an element such as comment is declared without a\n maxOccurs attribute, the element may not occur more than once. Be sure\n that if you specify a value for only the minOccurs attribute, it is\n less than or equal to the default value of maxOccurs, i.e. it is 0 or 1.\n Similarly, if you specify a value for only the maxOccurs attribute, it must be greater than or equal to the default value of minOccurs,\n i.e. 1 or more. If both attributes are omitted, the element must\n appear exactly once.\n\n* W3C XML Schema Part 1: Structures Second Edition \n```<element\n maxOccurs = (nonNegativeInteger | unbounded) : 1\n minOccurs = nonNegativeInteger : 1\n >\n\n```\n" } ]
[ { "from": "human", "value": "Were there any flying dinosaurs?" }, { "from": "gpt", "value": "Birds are both flying dinosaurs and flying reptiles. Yes, that's potentially confusing.\n\nTo 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.\n\nThe 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.\n\nSo 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.\nThe 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.\n\nA few words about pterosaurs\nAlong 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.\nThese images might help you understand the above explanation." } ]
[ { "from": "human", "value": "Say, a table ```car``` has one-to-one relationship to tables ```electric_car```, ```gas_car```, and ```hybrid_car```. If a ```car``` is ```electric_car```, it can no longer appear in ```gas_car``` or a ```hybrid_car```, etc. \nIs it a bad practice to have several mutually exclusive one-to-one relationships in database design?" }, { "from": "gpt", "value": "The different types of cars are an instance of a general problem that surfaces over and over again in data modeling. It is called \"generalization/specialization\" in ER modeling, and \"superclass/subclass\" in object modeling. \nAn object modeler uses the inheritance features built into the object model to solve the problem quite easily. The subclasses simply extend the superclass.\nThe relational modeler is faced with a problem. how to design the tables so as to emulate the benefits that one would get from inheritance? \nThe simplest technique is called single table inheritance. Data about all types of cars are grouped into a single table for cars. There is a column, car_type, that groups together all the cars of a single type. No car can belong to more than one type. If a column is irrelevant to, say, electric cars, it will be left NULL in the rows that pertain to electric cars.\nThis simple solution works well for the smaller and simpler cases. The presence of a lot of NULLs adds a tiny bit to storage overhead, and a little bit to retrieval overhead. The developer may have to learn SQL three-valued logic if boolean tests are done on nullable columns. This can be baffling at first, but one gets used to it.\nThere is another technique, called class table inheritance. In this design, there are separate tables for gas_car, electric_car, and hybrid_car, in addition to a combined table, car, for all of them. When you want all of the data about a specific kind of car, you join the car table with the appropriate specialized table. There are fewer NULLs in this design, but you do more joining. This technique works better in the larger and more complex cases.\nThere is a third technique called shared primary key. This technique is often used in conjunction with class table inheritance. The specialized tables for the subclasses have, as their primary key, a copy of the primary key of the corresponding entry in the car table. This id column can be declared to be both the primary key and a foreign key.\nThis involves a little extra programming when new cars are to be added, but it makes the joins simple, easy, and fast.\nSuperclasses and subclasses happen all the time in the real world. Don't be afraid. But do test your initial design for performance. If your first attempt is simple and sound, you'll be able to tweak it to speed it up." } ]
[ { "from": "human", "value": "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?" }, { "from": "gpt", "value": "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.\nThe few algorithms that Mathematica does support are not particularly well exposed for the type of tweaking needed to win Kaggle competitions.\nMathematica, as of version 10, supports the following classifiers: \"LogisticRegression\", \"Markov\", \"NaiveBayes\", \"NearestNeighbors\", \"NeuralNetwork\", \"RandomForest\", \"SupportVectorMachine\". \nWhilst 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. \nMathematica'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.\nA less often mentioned benefit is that use of Mathematica in a functional programming style tends to lead to fewer bugs in the final code." } ]
[ { "from": "human", "value": "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. \nWhat exactly is \"%1$s\" and \"%2$s\"? (Can anyone explain it in layman's terms?)" }, { "from": "gpt", "value": "The parameter ```'items_wrap'``` for ```wp_nav_menu()``` defaults to: \n```'%3$s'\n```\nThis a a template that is parsed with ```sprintf()```:\n```$nav_menu .= sprintf(\n $args->items_wrap\n, esc_attr( $wrap_id ) // %1$s\n, esc_attr( $wrap_class ) // %2$s\n, $items // %3$s\n);\n```\nThe 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.\nDo not change the type unless you really know what you do. :)\n\n* ```$wrap_id``` is the parameter ```'menu_id'``` if you have it set, else it is ```'menu-' . $menu->slug```.\n* ```$wrap_class``` is the parameter ```'menu_class'``` if you have it set, else it is empty.\n* ```$items``` is a string of the inner content of the menu.\n\nLet’s say you don’t need a ```class```. Just omit the second string:\n```wp_nav_menu( array( 'items_wrap' => '%3$s' ) );\n```\nIf you don’t need the ```class``` and the ```id```, and you want another container (because you used a custom walker):\n```wp_nav_menu( array( 'items_wrap' => '%3$s' ) );\n```\nThe 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." } ]
[ { "from": "human", "value": "I've noticed that people on YouTube and even on TV would sometimes say things like \"I used to take lots of coke a few years ago\" or \"I used to smoke weed daily until this and that\" or \"Yea, I smoke weed every once in a while,\" or \"I used to pirate games a lot when I was a bit younger\" or \"I used pirated Windows and Photoshop until I got a job,\" etc., etc..\nBasically they are confessing to a crime, on public record, couldn't anyone come after them? They've already confessed - technically all that would have to be done is a trial.\nHow do people publicly admit to criminal activity and not typically get arrested?" }, { "from": "gpt", "value": "Unless the Youtube Video shows them committing a crime, then no, they couldn't be arrested and tried for a crime. Them saying it, not under oath, is just hearsay that has no evidentiary value unless there is already other evidence they have committed a crime. In that case, its an admission. But there must be other, either circumstantial, or actual physical evidence of a crime.\n\nPast intoxication is not a crime, either. Possession of drugs, if caught with them is. But saying you got high is not.\n\nPeople have walked into police stations and confessed to murders. But with no evidence, no body, no name of a missing person, they can't even be held after the holding period for investigatory purposes expires. \n\nIf the video shows them committing assault, or breaking and entering (there actually are idiots who post this stuff), the video is actual evidence of a crime and it is often used against them. The statements can be used to begin an investigation, but people don't usually confess to anything worth pursuing even an investigation. The fact that someone says they used to do something criminal is not enough. For all you ( meaning anyone ) knows, the statute of limitations has expired because they \"pirated games\" 10 years ago. Your comment is right on." } ]
[ { "from": "human", "value": "Did two dissenting Supreme Court justices agree that Trump was \"absolutely immune\" to the Manhattan DA's subpoena?" }, { "from": "gpt", "value": "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.\nBased 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.\nJustice 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:\n\n* It does not interfere with the President's execution of his duties of office, and\n* It carries a weight of urgency — e.g., subpoenaing information related to suspected treason — as a guarantee it is not merely issued to harass.\n\nIn the absence of those conditions, in Alito's opinion, the President is only subject to the constitutional process of impeachment and trial in Congress.\nSo 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." } ]
[ { "from": "human", "value": "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?" }, { "from": "gpt", "value": "Halflings were originally called hobbits prior to a legal challenge.\nAccording 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:\n\nTSR 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.\n\nHalflings were originally called &quot;hobbits&quot; in the Dungeons & Dragons box set first released in 1974. Later printings changed this to &quot;halfling&quot;.\nAccording 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.\nDue 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.\nAccording 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." } ]
[ { "from": "human", "value": "My USB drive used to be originally 8GB when I bought it.\nI'm trying to reformatted in Windows 7 by right clicking on the drive and selecting ```Format...```. But the capacity only shows 250MB.\nIs there something I can do to get the original size back? Maybe it got partitioned in a weird way? \nThe flash drive is a SanDisk Cruzer Micro 8GB. " }, { "from": "gpt", "value": "The command line procedure is not simple, but it is the most likely thing to work. \nWhen 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.\n```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. \nProceed with extreme caution!\nOpen up a command prompt as administrator (open the start menu, type ```cmd``` and press Enter.)\nType ```diskpart``` and press Enter. You'll end up with a new prompt that looks like this:\n```DISKPART>\n```\nType\n```list disk \n```\nand you'll get a listing of all drives on your machine. \nType\n```select disk # \n```\nto 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.\nThen type\n```list partition \n```\nto get a listing of all partitions on the disk.\nIf you're sure you have the right disk/partition, you can then repeat typing\n```select partition # \ndelete partition \n```\nuntil all partitions are removed from that drive (you may need to type ```delete partition override``` for protected partitions).\nOnce 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\n```create partition primary \n```\nOnce you have created the partition, exit ```diskpart``` and, in the command promt, type \n```diskmgmt.msc \n```\nThis 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.\nThis should fix partition troubles on any readable USB flash drive." } ]
[ { "from": "human", "value": "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?" }, { "from": "gpt", "value": "Up to at least October 2013 the hidden services work like this:\n\n* A hidden service calculates its key pair (private and public key, asymmetric encryption).\n* Then the hidden service picks some relays as its introduction points.\n* It tells its public key to those introduction points over Tor circuits.\n* After that the hidden-service creates a hidden service descriptor, containing its public key and what its introduction points are.\n* The hidden service signs the hidden service descriptor with its private key.\n* It then uploads the hidden service descriptor to a distributed hash table (DHT).\n* 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.)\n* After retrieving the .onion address the client connects to the DHT and asks for that $hash.\n* If it exists the client learns about the hidden service's public key and its introduction points.\n* 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.\n* 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.\n* The client sends its message over a Tor circuit to one of the introduction points, demanding it to be forwarded to the hidden service.\n* The hidden service decrypts the introduce message with its private key to learn about the rendezvous point and the one-time secret.\n* The hidden service creates a rendezvous message, containing the one-time secret and sends it over a circuit to the rendezvous point.\n* The rendezvous point tells the client that a connection was established.\n* 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.\n" } ]
[ { "from": "human", "value": "I have been offered a PhD position by an inexperienced professor in a great institution in Europe. Despite the fact that the institution is very strong in my area, since the position was offered by this particular professor, I would have to commit myself to working with him for my thesis. This professor is young, and relatively inexperienced, but I enjoy the things he works on, and we seem to get along well.\nMy question is, would having an inexperienced advisor hurt my growth as a scientist, or my career in general? Will I have the time during my PhD to also work on the side with other, more renowned professors in the department, or is one usually focused in a single research project?" }, { "from": "gpt", "value": "An inexperienced advisor can hurt your career by being relatively unknown. This means they may not have access to the same network and that their recommendation letters do not carry the same weight. Inexperience in supervision may, for example, lead to unrealistic expectations. Or an inexperienced advisor can be very good for your career, by quickly rising to fame with the awesome publications the two of you will write together and being fresh in everybody's memory when writing recommendation letters. They may spend plenty of time on working with you.\n\nAn experienced advisor can hurt your career by being never there. They may already have made their name, have extremely high expectations from PhD students, to the level of cause them to be overly stressed and quit. Or they may be very good for your career, as dedicated as can be to PhD students, prioritising them above most other duties, having realistic expectations from PhD students, and having great influence when writing recommendation letters.\n\nBottom line: an experienced advisor may be better for you than an inexperienced one, but that certainly does not have to be the case. And keep in mind: a very good/famous scientist is not always a very good PhD advisor." } ]
[ { "from": "human", "value": "Is there a phrase that means \"too important\" and \"attracting too much attention\"?" }, { "from": "gpt", "value": "There is the term \"overdominant\":\n\nFrom Collins dictionary:\n\n>overdominant [adjective]\n excessively dominant\n To begin with, the design aspect is the most striking and arguably remains overdominant. [Times, Sunday Times (2010)]\n\n\nHere is an example:\n\n> [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...\n\nOther possible terms that have similar meaning include \"overpowered\", \"obtrusive\" and \"preponderant\"." } ]
[ { "from": "human", "value": "This guy claims that Olympic powerlifters working in the 1-6 rep range can increase strength without increasing muscle size. \n\n> Trained Olympic lifters, for example, were shown over a two-year period to have significant strength increases with barely noticeable increases in muscle mass (Hakkinen et al, 1988). I had a similar experience when I used AST's Max-OT principals. My strength went up like crazy, but I gained very little size. Obviously, traditional strength training with low volume and low sets (1-6 reps, 3 or less sets) is not the best approach. Strength training does cause hypertrophy (Hakkinen et al, 1985), but it won't cause maximum hypertrophy.\n\nWhat is the scientific explanation for this? Is the inverse true? That is, can a buff guy (with lots of prominent muscle) actually be weak? " }, { "from": "gpt", "value": "Certainly there is a correlation between muscle mass and strength, but there is more to the story. Two reasons why muscle mass and strength may not be completely congruous are:\n\n* Muscle fiber density\n* Muscle utilization\n\nDensity:\nYour muscles are composed of four different types of fibers (slow-twitch, and three forms of fast-twitch). These fibers have different profiles in terms of force applied and recovery time. Slow twitch fibers, for example, recover quickly but have less force as there are fewer muscle fibers per bundle, compared with the fast-twitch fibers. \nExtra water in the form of glycogen can also cause muscles to take up more volume with the same amount of actual muscle. This glycogen can be a ready source of energy for the muscles, but isn't going to increase their maximum theoretical force for a single heavy lift (per Olympic competition) where endurance through a long set isn't at issue.\nUtilization:\nThe average person is able to utilize 20-30% of their total theoretical muscle strength when trying their hardest. (Ref. Tsatsouline, Power To The People) Top lifters use perhaps 50% of their theoretical strength. Olympic and powerlifting-style training focuses on training the neural pathways to utilize a greater percentage of the available muscle mass. Since muscle fibers contract all internal cells (the all-or-nothing principal), this training is focused on convincing a greater proportion of fiber bundles to contract during a lift. \n\nCan a buff guy be weak? \nWell, it depends on your definition of buff. A cut guy can be weak (compared to a strength athlete), because muscle definition is more about having low body fat covering the muscle than it is about having large muscles. \nA bodybuilder with decent volume won't be able to lift as much as a comparable powerlifter because he/she doesn't train for strength per se. It seems worth noting that Olympic/power lifters also want to minimize their size (except for the heavyweights) because it affects their weight class in competition, so there is an added incentive to train for neural utilization over additional muscle mass." } ]
[ { "from": "human", "value": "What are the major concerns about planting trees to create carbon offsets?" }, { "from": "gpt", "value": "Here are some common concerns about using tree planting projects to create carbon offsets:\n\n* The scheme actually has a net positive effect, both in the short and long-term/\nHow effective a tree planting scheme is in capturing and storing carbon dioxide, is for a large part determined by what happens to the trees after they are planted. When trees mature and are harvested for wood that's used in construction, then the captured carbon dioxide is stored for a long time (until the wood decomposes or is burned). However, if no trees are replanted after harvesting this will have had a one-time effect only. Also when wood is burned (for energy or in a wild fire), or if trees die quickly and decompose, then their captured carbon is released again. Of course all trees die eventually even when they are not harvested, this is part of the natural cycle, but a mature forest can store a lot more carbon than a young, newly-planted forest so it's important to keep a forest intact as much as possible.\n\n* The wrong type(s) of trees are planted in the wrong location.\nIn the past there were bad offsetting schemes that planted non-native trees, or planted trees in a location where they would change water flows and thus change local ecosystems in a negative way. Some offsetting schemes planted thousands of trees of the same species, resulting in a large monoculture. Such a monoculture hinders biodiversity, is susceptible to diseases and can even damage local communities.\nThere have also been reports that planting trees above a certain latitude can have a net warming effect by changing the albedo and trapping heat. \n\n* Buying offsets reduces the incentive for people to reduce their emissions.\nReducing emissions is much more effective than offsetting. Buying carbon offsets can lead to people thinking they are doing the right thing, whereas they had better spent their time and effort in reducing their emissions. Of course this point goes for all offsetting-schemes and is not specifically for planting trees.\n\n* There are more effective ways of reducing carbon emissions than planting trees.\nNowadays many offsetting schemes invest in development of renewable energy sources (in developing countries) instead of planting trees, simply because it is a more effective and cheaper way to reduce emissions." } ]
[ { "from": "human", "value": "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$?" }, { "from": "gpt", "value": "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.\nIn 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.\nThere 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.\nGeneral 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. " } ]
[ { "from": "human", "value": "In Shutter Island, at the end of the movie Teddy had a chat with Chuck, in that scene Teddy told to Chuck as,\n\n Which would be worse: To live as a monster, or to die as a good man?\n\nWhat's the implicit meaning of this dialogue? Who's the monster as Teddy mentioned?\nAnd, who's a good man?" }, { "from": "gpt", "value": "To Live as a Monster\nIf 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. \nTo die as a good man\nIn 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. \nWhat 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. \nBy 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. " } ]
[ { "from": "human", "value": "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.\n\n\n```#box {\n display: flex;\n width: 100px;\n margin: 0 -5px;\n}\n.item {\n background: gray;\n width: 50px;\n height: 50px;\n margin: 0 5px;\n}```\n```\n \n \n \n \n```\n\n\n" }, { "from": "gpt", "value": "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.\nWe are using ```display: grid;``` and its properties.\n\n\n```#box {\n display: grid;\n width: 100px;\n grid-gap: 5px;\n /* Space between items */\n grid-template-columns: repeat(4,1fr);\n /* Decide the number of columns(4) and size(1fr | 1 Fraction | you can use pixels and other values also) */\n}\n.item {\n background: gray;\n width: 100%;\n /* 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%** */\n height: 50px;\n}```\n```\n \n \n \n \n \n \n \n \n```\n\n\n\nThe Downside of this method is in Mobile Opera Mini will not be supported and in PC this works only after IE10.\nNote for complete browser compatability including IE11 please use Autoprefixer\n\nOLD ANSWER\nDon'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.\nThis 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.\n```.item+.item{\n margin-left: 5px;\n}\n```\nThe below code will do the trick. In this method, there is no need to give ```margin: 0 -5px;``` to the ```#box``` wrapper.\nA working sample for you:\n\n\n```#box {\n display: flex;\n width: 100px;\n}\n.item {\n background: gray;\n width: 22px;\n height: 50px;\n}\n.item+.item{\n margin-left: 5px;\n}```\n```\n \n \n \n \n```\n\n\n" } ]
[ { "from": "human", "value": "Is there a Git for data? The key improvement I'd want is to Diff/Merge more intelligently. e.g. in CSV rather than line vs line comparison, it would do cell vs cell.\nAnd ordering is usually not significant, e.g. rows in a CSV, whereas Git does care and presents the user with 'conflicts'." }, { "from": "gpt", "value": "Please note that ```git``` has two configuration commands:\n```git config filter..clean\ngit config filter..smudge\n```\nThe ```clean``` filter can be used e.g. to sort all records in a CSV file except the top row, thus making re-ordering irrelevant.\nQuoting ```gitattributes(5)``` :\n\nA filter driver consists of a clean command and a smudge command, either of which can be left unspecified. Upon checkout, when the smudge command is specified, the command is fed the blob object from its standard input, and its standard output is used to update the worktree file. Similarly, the clean command is used to convert the contents of worktree file upon checkin.\nA missing filter driver definition in the config is not an error but makes the filter a no-op passthru.\nThe content filtering is done to massage the content into a shape that is more convenient for the platform, filesystem, and the user to use. The key phrase here is &quot;more convenient&quot; and not &quot;turning something unusable into usable&quot;. In other words, the intent is that if someone unsets the filter driver definition, or does not have the appropriate filter program, the project should still be usable.\n" } ]
[ { "from": "human", "value": "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.\nIt 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.\nIt seems to be a convention, but should the OK/Cancel buttons be aligned right or centered?\nShould the OK/Cancel buttons be aligned right or centered?" }, { "from": "gpt", "value": "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.\nForms 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).\nSmall 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.\nIn the end, the heuristic is this:\n\n* Large Windows & Forms get the button on the bottom left.\n* Small Windows & Dialogues get the button on the bottom right.\n\nNote the buttons on stackexchange sites:\n\n* Post Your Answer button at the bottom-left of the longer form\n\n* Add Comment button to the right of a small field\n\nFurthermore, 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!\nWe'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." } ]
[ { "from": "human", "value": "Is it at all possible to update object's properties with ```setState```?\nSomething like:\n```this.state = {\n jasper: { name: 'jasper', age: 28 },\n}\n```\nI have tried: \n```this.setState({ 'someOtherName'});\n```\nand this:\n```this.setState({jasper: {name: 'someothername'}})\n```\nThe first results in a syntax error and the second just does nothing. Any ideas?" }, { "from": "gpt", "value": "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```.\n1- Simplest one:\nFirst create a copy of ```jasper``` then do the changes in that:\n```this.setState(prevState => {\n let jasper = Object.assign({}, prevState.jasper); // creating copy of state variable jasper\n = 'someothername'; // update the name property, assign a new value\n return { jasper }; // return new object jasper object\n})\n```\nInstead of using ```Object.assign``` we can also write it like this:\n```let jasper = { ...prevState.jasper };\n```\n2- Using spread syntax:\n```this.setState(prevState => ({\n jasper: { // object that we want to update\n ...prevState.jasper, // keep all other key-value pairs\n name: 'something' // update the value of specific key\n }\n}))\n```\nNote: ```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.\n\nUpdating nested state object:\nAssume you have defined state as:\n```this.state = {\n food: {\n sandwich: {\n capsicum: true,\n crackers: true,\n mayonnaise: true\n },\n pizza: {\n jalapeno: true,\n extraCheese: false\n }\n }\n}\n```\nTo update extraCheese of pizza object:\n```this.setState(prevState => ({\n food: {\n, // copy all other key-value pairs of food object\n pizza: { // specific object of food object\n, // copy all pizza key-value pairs\n extraCheese: true // update value of specific key\n }\n }\n}))\n```\nUpdating array of objects:\nLets assume you have a todo app, and you are managing the data in this form:\n```this.state = {\n todoItems: [\n {\n name: 'Learn React Basics',\n status: 'pending'\n }, {\n name: 'Check Codebase',\n status: 'pending'\n }\n ]\n}\n```\nTo 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.\n```let key = 2;\nthis.setState(prevState => ({\n todoItems:\n el => el.key === key? { ...el, status: 'done' }: el\n )\n}))\n```\nSuggestion: If object doesn't have a unique value, then use array index." } ]
[ { "from": "human", "value": "What is the difference between Non-Player Characters (NPCs) and bots in video games?" }, { "from": "gpt", "value": "The key distinction is that a Bot represents an automated player; an NPC, by contrast, isn't playing the game at all.\n\nIn 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.\n\nA 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." } ]
[ { "from": "human", "value": "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?" }, { "from": "gpt", "value": "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:\n\n* Declare your class ```final``` - Prevents extension of the class since extending a static class makes no sense\n* Make the constructor ```private``` - Prevents instantiation by client code as it makes no sense to instantiate a static class\n* 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\n* 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\n\nSimple example per suggestions from above:\n```public class TestMyStaticClass {\n public static void main(String []args){\n MyStaticClass.setMyStaticMember(5);\n System.out.println(\"Static value: \" + MyStaticClass.getMyStaticMember());\n System.out.println(\"Value squared: \" + MyStaticClass.squareMyStaticMember());\n // MyStaticClass x = new MyStaticClass(); // results in compile time error\n }\n}\n// A top-level Java class mimicking static class behavior\npublic final class MyStaticClass {\n private MyStaticClass () { // private constructor\n myStaticMember = 1;\n }\n private static int myStaticMember;\n public static void setMyStaticMember(int val) {\n myStaticMember = val;\n }\n public static int getMyStaticMember() {\n return myStaticMember;\n }\n public static int squareMyStaticMember() {\n return myStaticMember * myStaticMember;\n }\n}\n```\nWhat 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." } ]
[ { "from": "human", "value": "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.\nBut I did. In all the novels and comics that came out after \"Return of the Jedi\", the Emperor's name was stated plainly: Palpatine. \nSo 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? \nMaybe 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?\nWhat was the intent?" }, { "from": "gpt", "value": "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.\nSo 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.\nThe 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." } ]
[ { "from": "human", "value": "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. " }, { "from": "gpt", "value": "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. :)\nYou 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).\nFirst four books, he's clumsy, and is not yet showing any magical talent.\nStarting with the fifth year, Neville is shown to have been changed, and repeatedly proves his bravery and willingness to fight.\nNOTE: 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.\nThere'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.\n\nFifth year\n\n* He joins DA\n\n* He shows marked and significant improvement in his magical abilities while in DA\n\n* 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:\n\nNeville: &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;\nHarry: &quot;No — of course it wasn't —&quot;\nNeville: &quot;Then we should come too. We want to help.&quot;\n\n\n* During the battle at the Ministry, he refused to leave as per Harry's suggestion after Dolohov broke Neville's nose and wand.\n\n* When being threatened and tortured by Death Eaters, he told Harry not to give them the Prophecy\n\n\nSixth year\n\n* 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.\n\n\nSeventh year\n\n* 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.\n\n* along with Ginny and Luna, restarted Dumbledore's Army.\n\n* attempted to steal Godric Gryffindor's Sword from Snape's office\n\n* 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.\n\n* 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.\n\n* 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.\n\n* 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.\n\n* 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.\n\nAll in all, pretty convincing evidence of someone's bravery." } ]
[ { "from": "human", "value": "This claim was made popular by being said in the movie The Social Network. It exactly says:\n\n> 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?\n" }, { "from": "gpt", "value": "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.\n\nYou 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.\n\nThe 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.\nThe 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. \n\nThe 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.\nTaking 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.\nIf you take the 15 SD value of 1/261 then you get only about 5,251,000 Chinese geniuses.\nWith 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.\nConclusion: This claim is wrong according to the definition and probabilities of the IQ.\n\nSupplement:\nIt 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." } ]
[ { "from": "human", "value": "I am trying to get my program to print out ```\"banana\"``` from the dictionary. What would be the simplest way to do this?\nThis is my dictionary: \n```prices = {\n \"banana\" : 4,\n \"apple\" : 2,\n \"orange\" : 1.5,\n \"pear\" : 3\n}\n```" }, { "from": "gpt", "value": "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```\n\nChanged in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6.\n\nsource\n\nPython 3.6 and earlier*\nIf 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.\nIf you need to keep things in order, then you have to use an ```OrderedDict``` and not just a plain dictionary.\n```import collections\nprices = collections.OrderedDict([\n (&quot;banana&quot;, 4),\n (&quot;apple&quot;, 2),\n (&quot;orange&quot;, 1.5),\n (&quot;pear&quot;, 3),\n])\n```\nIf you then wanted to see all the keys in order you could do so by iterating through it\n```for k in prices:\n print(k)\n```\nYou could, alternatively put all of the keys into a list and then work with that\n```keys = list(prices)\nprint(keys[0]) # will print &quot;banana&quot;\n```\nA 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\n```>>> next(iter(prices))\n'banana'\n```\n* CPython had guaranteed insertion order as an implementation detail in 3.6." } ]
[ { "from": "human", "value": "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?" }, { "from": "gpt", "value": "\n\n* 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.\n* 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.\n* From a price perspective, green beans of Robusta is about half the price of Arabica green beans on the commodity market.\n* 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.\n\nAll 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.\nWhere 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.\nOne 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.\n\n* Robusta beans are much more circular, whereas Arabica are more oval.\n* Chlorogenic acid is a significant antioxidant and an insect deterrent. Robusta is 7-10% CGA and Arabica has 5.5-8% CGA." } ]
[ { "from": "human", "value": "So whenever we want to shoot our flash before taking a photo. we have to charge it first.\nWhat is the point of the charging our flashes? Aren't their power directly supplied by the battery of our camera?\nPlease answer for the built in flash on the 2000D and the traditional hot shoe Xenon flashes.\nPerhaps these hot shoe xenon flashes have their own batteries charged by the slow hot shoe port. Who knows? " }, { "from": "gpt", "value": "The peak power at work when a flash is being discharged is extreme.\nExample: 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.\nA 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.\nYour 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.\nIf 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). \nAlso, 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)." } ]
[ { "from": "human", "value": "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." }, { "from": "gpt", "value": "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.\nHere are some things to consider that may help you and your colleagues cope with the added stress and emotions following a layoff:\n\n* 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.\n* 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.\n* 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.\n* 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.\n* 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.\n* 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.\n" } ]
[ { "from": "human", "value": "Could you please clearly explain what is the difference between correlation and convolution that is done by a filter on an image? \nI 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?\nThanks" }, { "from": "gpt", "value": "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. \nThe 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.\nThe 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.\nSo 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." } ]
[ { "from": "human", "value": "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)?" }, { "from": "gpt", "value": "Yes: it corresponds to the date of Hugo's conception.\nThis 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:\n\nBut 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.\n-- p. 162 (emphasis mine)\n\nAs 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:\n\nGaudon 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).\n-- p. 165 (emphasis mine)\n" } ]
[ { "from": "human", "value": "Why does Michael Crichton use US Customary measurements in hard sci-fi?" }, { "from": "gpt", "value": "Crichton used both imperial and metric, depending on the context.\nIn the course of one paragraph in The Sphere, he managed to use both!\n\n> \"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.\"\n\nWhen the character (Barnes, a Navy captain) is talking about precise measurements, he uses metric. When he's being more general, he uses imperial.\nThe main character Norman (a psychologist, not exactly the most mathematically intensive field) uses imperial when thinking to himself.\n\n> He climbed up through the submarine and into a round steel cylinder approximately eight feet in diameter.\n\nBut later, when the astrophysicist Ted is giving officialish measurements the titular sphere, he uses metric:\n\n> \"This object is a burnished sphere approximately ten meters in a diameter, no solid, and composed of a dense metal alloy.\"\n\nSo 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." } ]
[ { "from": "human", "value": "How can horns, most of which have only three buttons, play all their notes?" }, { "from": "gpt", "value": "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.\nOn 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.\nLet'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.\nThat'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.\nSo 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.\nNow, 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!" } ]
[ { "from": "human", "value": "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?" }, { "from": "gpt", "value": "Aliens are alien, without a common background their motives may be incomprehensible.\nIf 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:\n\n* 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.\n* Tourism; experiencing a culture that is vastly different from your previous experiences.\n* Reality TV; Bear Grylls.\n* Method Acting; preparing for a role in their own entertainment channels that involves playing the part of a member of an Information Age society.\n* Challenge; because they can.\n* 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.\n* 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.\n* 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.\n* 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)." } ]
[ { "from": "human", "value": "I've taken a look at the list of surveys taken on and noticed a curious question: \"Can you name all the uses of “_”?\". Can you? If yes, please do so here. Explanatory examples are appreciated." }, { "from": "gpt", "value": "The following is an explanation of the uses of the underscore is Scala _ [underscore] magic.\nExamples:\n``` def matchTest(x: Int): String = x match {\n case 1 => \"one\"\n case 2 => \"two\"\n case _ => \"anything other than one and two\"\n }\n expr match {\n case List(1,_,_) => \" a list with three element and the first element is 1\"\n case List(_*) => \" a list with zero or more elements \"\n case Map[_,_] => \" matches a map with any key type and any value type \"\n case _ =>\n }\n List(1,2,3,4,5).foreach(print(_))\n // Doing the same without underscore:\n List(1,2,3,4,5).foreach( a => print(a))\n```\nIn Scala, ```_``` acts similar to ```*``` in Java while importing packages.\n```// Imports all the classes in the package matching\nimport scala.util.matching._\n// Imports all the members of the object Fun (static import in Java).\nimport com.test.Fun._\n// Imports all the members of the object Fun but renames Foo to Bar\nimport com.test.Fun.{ Foo => Bar , _ }\n// Imports all the members except Foo. To exclude a member rename it to _\nimport com.test.Fun.{ Foo => _ , _ }\n```\nIn 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.\n```class Test {\n private var a = 0\n def age = a\n def age_=(n:Int) = {\n require(n>0)\n a = n\n }\n}\n```\nUsage:\n```val t = new Test\nt.age = 5\nprintln(t.age)\n```\nIf 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.\n```class Test {\n def fun = {\n // Some code\n }\n val funLike = fun _\n}\n```" } ]
[ { "from": "human", "value": "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?" }, { "from": "gpt", "value": "There are several reasons why such internal policies exist:\n\n* Your institution may get a discount on certain services of the travel agent if it buys enough from the agent\n* 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\n* 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.\n* 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)\n* 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.\n\nWhich of these reasons is the one why this policy exists can only be answered by the responsible employees of your institution." } ]
[ { "from": "human", "value": "Layman's explanation of encryption backdoors" }, { "from": "gpt", "value": "There are two somewhat orthogonal concepts in backdooring encryption algorithms:\n\n* The backdoor can be explicit or implicit. An explicit backdoor is one that everybody knows it is there. An implicit backdoor strives at remaining undetected by the algorithm owners. Of course, when there is an explicit backdoor, people tend to avoid the algorithm altogether, so explicit backdoors may hope to work only in the presence of a legal framework that forces implementers to use the backdoored system.\nAn example of an explicit backdoor is the Clipper chip (which was ultimately abandoned). The backdoor is not really in the algorithm, more in the assembly of algorithms into a protocol, and technically it was an automatic key escrowing method. For an implicit backdoor, see the Dual EC DRBG as a famous example: it worked only as long as nobody was aware that it was backdoored.\n* The backdoor's security may be quantifiable, or not. In the case of Dual EC DRBG, the mechanism uses well-trodden mathematical paths: the NSA knew that exploiting the backdoor required knowledge of an internal secret key, based on discrete logarithm (on elliptic curves).\nA non-quantifiable security is what happens when you try to push, for instance, a voluntarily flawed algorithm, or one for which you know of a cryptanalytic method that you did not publish. This is a very dangerous game for a spy agency, because you cannot really know whether third parties could find the flaw or not. Such backdooring tends to backfire in the long term.\nInterestingly, the NSA tends not to use non-quantifiable backdoors. A good example is DES. At the time it was designed, the NSA believed that it could tackle an upfront 256 exhaustive search, and that nobody else (in particular the Soviets) had the technology and budget for that. The NSA also knew of a novel cryptanalytic method (differential cryptanalysis). So when the NSA intervened in the design of DES, it insisted on shortening the key from 64 to 56 bits (that's addition of a quantifiable backdoor, and it was rather obvious, so quasi-explicit), and also on strengthening the design against differential cryptanalysis. This is a good example about how NSA consciously refrained from a non-quantifiable backdoor. There is only one thing that spy agencies fear more than not being able to spy: it is the idea that other competing spy agencies may also spy.\n\nSo a real, good backdoor is one that uses maths to offer quantifiable security against unauthorized usage of the backdoor. It is extremely difficult to have quantifiable security without making the backdoor explicit. The \"best in class\" in that area is Dual EC DRBG, and even before the Snowden business, cryptographers were already finding it weird and strongly suspected foul play (see the analyses back in 2007, 6 years before Snowden)." } ]
[ { "from": "human", "value": "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.\nWhen 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.\nI am using this code to make it move the selected option to the top of the div:\n```var pathArray = window.location.pathname.split( '/' );\nvar el = document.getElementById(pathArray[5]);\nel.scrollIntoView(true);\n```\nIt moves it to the top of the div but about 10 pixels too far up.\nhow to fix that?" }, { "from": "gpt", "value": "CSS ```scroll-margin``` and ```scroll-padding```\nYou 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.\nFor your example, you would want to add ```scroll-margin-top``` for the element that you want to scroll into view, like this:\n```.example {\n scroll-margin-top: 10px;\n}\n```\nThis affects ```scrollIntoView``` code, like this code:\n```const el = document.querySelector(&quot;.example&quot;);\nel.scrollIntoView({block: &quot;start&quot;, behavior: &quot;smooth&quot;});\n```\nThis 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:\n\n* ```padding-top```\n* ```border-top```\n* ```scroll-margin-top```\n* (and not ```margin-top```)\n\nIn addition, if the ```html``` element has ```scroll-padding-top``` set, then that is taken into account too.\nIf 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())`" } ]
[ { "from": "human", "value": "Suppose I have the geographic coordinates of &quot;Saratoga, California, USA&quot; as\n```Latitude: 37°15.8298′ N\nLongitude: 122° 1.3806′ W\n```\nI know from here that in the case of latitude ```1° ≈ 69 miles``` and that longitude varies:\n```1° longitude = cosine (latitude) * length of degree (miles) at Equator.\n```\nHow many miles is 1° longitude at ```longitude: 122°1.3806′ W```?" }, { "from": "gpt", "value": "It doesn't matter at what longitude you are. What matters is what latitude you are.\nLength of ```1 degree of Longitude``` = ```cosine (latitude in radians) * length of degree (miles) at equator```.\nConvert your latitude into decimal degrees ~ 37.26383\nConvert your decimal degrees into radians ~ 0.65038\nTake the cosine of the value in radians ~ 0.79585\n1 degree of Longitude = ~0.79585 * 69.172 = ~ 55.051 miles\nMore useful information from the website:\n\nDegrees of latitude are parallel so the distance between each degree\nremains almost constant but since degrees of longitude are farthest\napart at the equator and converge at the poles, their distance varies\ngreatly.\nEach degree of latitude is approximately 69 miles (111 kilometers)\napart. The range varies (due to the earth's slightly ellipsoid shape)\nfrom 68.703 miles (110.567 km) at the equator to 69.407 (111.699 km)\nat the poles. This is convenient because each minute (1/60th of a\ndegree) is approximately one [nautical] mile.\nA degree of longitude is widest at the equator at 69.172 miles\n(111.321) and gradually shrinks to zero at the poles. At 40° north or\nsouth the distance between a degree of longitude is 53 miles (85 km)\n\nNote that the original site ( erroneously omitted the &quot;nautical&quot; qualifier." } ]
[ { "from": "human", "value": "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?\nCiting Wikipedia:\n\n > 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." }, { "from": "gpt", "value": "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”).\nBut they're indistinguishable and don't have any major differences between them.\nValhalla 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.” \nSimilarily, entrance to Folkvang is dependent upon being selected by Freya.\n\n 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.\n source: Ellis, Hilda Roderick. 1968. The Road to Hel: A Study of the Conception of the Dead in Old Norse Literature. p. 85-86. \n\n\n\n \n * Folkvang is the ninth, and there Freyia arranges\n the choice of seats in the hall;\n half the slain she chooses every day,\n and half Odin owns.\n \n source: 1996 Carolyne Larrington in The Poetic Edda “Grimnir’s Sayings”\n\nThe 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.\nComing to the second part of the question:\n\n And why did the need to have many \"paradises\" (whatever you many call it) exist?\n\nHel is a place where all humans have to go after their death:\n\n “For there is a time\n when every man shall journey hence to Hel.\"\n Fáfnismál 10\n\nSo before the dead finally reach Hel, Odin and Freyja select the ones who are worthy of living in Valhalla and Folkvang. \nTherefore,\n\n* Valhalla receives distinguished warriors.\n* Folkvangr receives the rest of the warriors.\n* Hel receives the rest of the dead.\n\n\nsource:" } ]
[ { "from": "human", "value": "I noticed that there is a binary executable ```/bin/echo``` on my Ubuntu MATE 17.04 system.\nI thought, that's odd, because\n```$ type echo\necho is a shell builtin```\nCursory testing suggests that ```/bin/echo``` does the same sort of thing as the Bash builtin ```echo```:\n```$ /bin/echo foo\nfoo\n$ /bin/echo $USER\nzanna\n```\nSo, why is there another version of ```echo``` separate from the Bash program, and why or when would I want to use it?" }, { "from": "gpt", "value": "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:\n\n* You're not always using a shell. Under a variety of circumstances, you run an executable directly and not through a shell.\n* At least in theory, some shells don't have an ```echo``` builtin. This is not actually required.\n\nTo 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:\n```find src -name 'abc*' -type f -exec mv -nv {} dest/ \\;\n```\nBut 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:\n```find src -name 'abc*' -type f -exec echo mv -nv {} dest/ \\;\n```\nBut ```find``` doesn't use a shell. That runs ```/bin/echo```.\nBesides ```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.\nSimilarly, some shells have a ```printf``` builtin but ```/usr/bin/printf``` also exists.\nA 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.\nIn ```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:\n```$ type -a echo\necho is a shell builtin\necho is /bin/echo\n```" } ]
[ { "from": "human", "value": "what's the difference between JavaScript objects, classes and functions?" }, { "from": "gpt", "value": "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.\nIn 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;```.\nFunctions 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.\nThe 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.\n" } ]
[ { "from": "human", "value": "In most introductory algorithm classes, notations like $O$ (Big O) and $\\Theta$ are introduced, and a student would typically learn to use one of these to find the time complexity.\nHowever, there are other notations, such as $o$, $\\Omega$ and $\\omega$. Are there any specific scenarios where one notation would be preferable to another?" }, { "from": "gpt", "value": "You are referring to the Landau notation. They are not different symbols for the same thing but have entirely different meanings. Which one is \"preferable\" depends entirely on the desired statement.\n$f \\in \\cal{O}(g)$ means that $f$ grows at most as fast as $g$, asymptotically and up to a constant factor; think of it as a $\\leq$. $f \\in o(g)$ is the stricter form, i.e. $\n$f \\in \\Omega(g)$ has the symmetric meaning: $f$ grows at least as fast as $g$. $\\omega$ is its stricter cousin. You can see that $f \\in \\Omega(g)$ is equivalent to $g \\in \\cal{O}(f)$.\n$f \\in \\Theta(g)$ means that $f$ grows about as fast as $g$; formally $f \\in \\cal{O}(g) \\cap \\Omega(g)$. $f \\sim g$ (asymptotic equality) is its stronger form. We often mean $\\Theta$ when we use $\\cal{O}$.\nNote how $\\cal{O}(g)$ and its siblings are function classes. It is important to be very aware of this and their precise definitions -- which can differ depending on who is talking -- when doing \"arithmetics\" with them. \nWhen proving things, take care to work with your precise definition. There are many definitions for Landau symbols around (all with the same basic intuition), some of which are equivalent on some sets on functions but not on others.\n\nIf you are interested in using Landau notation in a rigorous and sound manner, you may be interested in a work by Rutanen et al.. They formulate necessary and sufficient criteria for asymptotic notation as we use them in algorithmics, show that the common definition fails to meet them and provide a (the, in fact) workable definition.\n\n* A general definition of the O-notation for algorithm analysis by K. Rutanen et al. (2015)\n" } ]
[ { "from": "human", "value": "Why is Gaia operating around Earth orbit? Why not send it to Neptune's orbit?" }, { "from": "gpt", "value": "Well, you thought about the spatial aspect of a parallax measurement, but not about the temporal one.\nGaia'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.\nFor 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.\nIt 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.\nCompare that to Gaia's predecessor, the Hipparcos satellite, which was parked in geostationary orbit.\nNow 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." } ]
[ { "from": "human", "value": "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```:\n```>>>import time\n>>>print time.strftime(&quot;%B %d %Y&quot;, &quot;1284101485&quot;)\nTraceback (most recent call last):\n File &quot;&quot;, line 1, in \nTypeError: argument must be 9-item sequence, not str\n```" }, { "from": "gpt", "value": "There are two parts here:\n\n* Convert the unix timestamp (\"seconds since epoch\") to the local time\n* Display the local time in the desired format.\n\nA 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:\n```#!/usr/bin/env python\nfrom datetime import datetime\nimport tzlocal # $ pip install tzlocal\nunix_timestamp = float(\"1284101485\")\nlocal_timezone = tzlocal.get_localzone() # get pytz timezone\nlocal_time = datetime.fromtimestamp(unix_timestamp, local_timezone)\n```\nTo display it, you could use any time format that is supported by your system e.g.:\n```print(local_time.strftime(\"%Y-%m-%d %H:%M:%S.%f%z (%Z)\"))\nprint(local_time.strftime(\"%B %d %Y\")) # print date in your format\n```\n\nIf you do not need a local time, to get a readable UTC time instead:\n```utc_time = datetime.utcfromtimestamp(unix_timestamp)\nprint(utc_time.strftime(\"%Y-%m-%d %H:%M:%S.%f+00:00 (UTC)\"))\n```\n\nIf 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:\n```local_time = datetime.fromtimestamp(unix_timestamp)\nprint(local_time.strftime(\"%Y-%m-%d %H:%M:%S.%f\"))\n```\nOn 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):\n```#!/usr/bin/env python3\nfrom datetime import datetime, timezone\nutc_time = datetime.fromtimestamp(unix_timestamp, timezone.utc)\nlocal_time = utc_time.astimezone()\nprint(local_time.strftime(\"%Y-%m-%d %H:%M:%S.%f%z (%Z)\"))\n```\nFunctions 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:\n```#!/usr/bin/env python\nimport time\nunix_timestamp = int(\"1284101485\")\nutc_time = time.gmtime(unix_timestamp)\nlocal_time = time.localtime(unix_timestamp)\nprint(time.strftime(\"%Y-%m-%d %H:%M:%S\", local_time))\nprint(time.strftime(\"%Y-%m-%d %H:%M:%S+00:00 (UTC)\", utc_time))\n```" } ]
[ { "from": "human", "value": "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:\n```mysite/\n\n mysite/ --> (, etc)\n myapp/ --> (,, etc)\n static/\n```\nIn ```mysite/``` I have:\n```STATIC_ROOT = 'staticfiles'\n```\nSo when I run the command:\n```python collectstatic\n```\nIt creates a folder called ```staticfiles``` at the root level (so same directory as ```myapp/```)\nWhat's the point of this? Isn't it just creating a copy of all my static files?" }, { "from": "gpt", "value": "## Collect static files from multiple apps into a single path\n\nA single Django project may use several apps, so while there you only have one ```myapp```, it may actually be ```myapp1```, ```myapp2```, etc\nBy 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.\n\n## Persistent URLs with ManifestStaticFilesStorage\n\nA 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)\nThe MD5 hash will kick in e.g. if you set it to use ```ManifestStaticFilesStorage```, which adds that behavior.\n\n> 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." } ]
[ { "from": "human", "value": "I am used to thinking of finite-differences as a special case of finite-elements, on a very constrained grid. What are criteria to choose between finite-differences and finite-elements" }, { "from": "gpt", "value": "It is possible to write most specific finite difference methods as Petrov-Galerkin finite element methods with some choice of local reconstruction and quadrature, and most finite element methods can also be shown to be algebraically equivalent to some finite difference method. Therefore, we should choose a method based on which analysis framework we want to use, which terminology we like, which system for extensibility we like, and how we would like to structure software. The following generalizations hold true in the vast majority of variations in practical use, but many points can be circumvented.\nFinite Difference\nPros\n\n* efficient quadrature-free implementation\n* aspect ratio independence and local conservation for certain schemes (e.g. MAC for incompressible flow)\n* robust nonlinear methods for transport (e.g. ENO/WENO)\n* M-matrix for some problems\n* discrete maximum principle for some problems (e.g. mimetic finite differences)\n* diagonal (usually identity) mass matrix\n* inexpensive nodal residual permits efficient nonlinear multigrid (FAS)\n* cell-wise Vanka smoothers give efficient matrix-free smoothers for incompressible flow\n\nCons\n\n* more difficult to implement \"physics\"\n* staggered grids are sometimes quite technical\n* higher than second order on unstructured grids is difficult\n* no Galerkin orthogonality, so convergence may be more difficult to prove\n* not a Galerkin method, so discretization and adjoints do not commute (relevant to optimization and inverse problems)\n* self-adjoint continuum problems often yield non-symmetric matrices\n* solution is only defined pointwise, so reconstruction at arbitrary locations is not uniquely defined\n* boundary conditions tend to be complicated to implement\n* discontinuous coefficients usually make the methods first order\n* stencil grows if physics includes \"cross terms\"\n\nFinite Element\nPros\n\n* Galerkin orthogonality (discrete solution to coercive problems is within a constant of the best solution in the space)\n* simple geometric flexibility\n* discontinuous Galerkin offers robust transport algorithm, arbitrary order on unstructured grids\n* cellwise entropy inequality guaranteeing $L^2$ stability holds independent of mesh, dimension, order of accuracy, and presence of discontinuous solutions, without needing nonlinear limiters\n* easy of implementing boundary conditions\n* can choose conservation statement by choosing test space\n* discretization and adjoints commute (for Galerkin methods)\n* elegant foundation in functional analysis\n* at high order, local kernels can exploit tensor product structure that is missing with FD\n* Lobatto quadrature can make methods energy-conserving (assuming a symplectic time integrator)\n* high order accuracy even with discontinuous coefficients, as long as you can align to boundaries\n* discontinuous coefficients inside elements can be accommodated with XFEM\n* easy to handle multiple inf-sup conditions\n\nCons\n\n* many elements have trouble at high aspect ratio\n* continuous FEM has trouble with transport (SUPG is diffusive and oscillatory)\n* DG usually has more degrees of freedom for same accuracy (though HDG is much better)\n* continuous FEM does not provide cheap nodal problems, so nonlinear smoothers have much poorer constants\n* usually more nonzeros in assembled matrices\n* have to choose between consistent mass matrix (some nice properties, but has full inverse, thus requiring an implicit solve per time step) and lumped mass matrix.\n" } ]
[ { "from": "human", "value": "How important is multithreading in the current software industry?" }, { "from": "gpt", "value": "It is extremely important.\nWhat 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:\n\n* 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.\n* Computers are now heavily networked and modern applications rely upon being able to fetch rich information from a variety of sources.\n\nFrom 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. \nSo 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. \nThe 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." } ]
[ { "from": "human", "value": "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?" }, { "from": "gpt", "value": "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.\nThe 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.\nThe 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.\nSome 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.\nDiamonds 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." } ]
[ { "from": "human", "value": "Normal filesystem images can be easily mounted:\n```mount system.img /mnt\n```\nExamined, and modified. But when I try this with a Raspberry Pi system image (e.g. raspbian), I get:\n```mount: unknown filesystem type '(null)'\n```\nAnd no matter what I try with ```-t```, it won't work. How can I mount this image?" }, { "from": "gpt", "value": "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:\n```Device Boot Start End Blocks Id System\nwhatever.img1 8192 122879 57344 c W95 FAT32 (LBA)\nwhatever.img2 122880 5785599 2831360 83 Linux\n```\nThese 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:\n```Units: sectors of 1 * 512 = 512 bytes\n```\nWe can find the offset in bytes by multiplying this unit size by the ```Start``` block of the partition:\n\n* 1st partition 512 * 8192 = 4194304\n* 2nd partition 512 * 122880 = 62914560\n\nThese 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:\n```mount -v -o offset=4194304 -t vfat whatever.img /mnt/img/one\nmount -v -o offset=62914560 -t ext4 whatever.img /mnt/img/two\n```\nIf 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):\n```mount -v -o offset=4194304,sizelimit=29360128 \\\n -t vfat whatever.img /mnt/img/one\n```\nThe second partition doesn't need a sizelimit since there's nothing after it in the image. \nYou 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.\nNote that the first partition is probably mounted on ```/boot``` in the second partition when the system is running." } ]
[ { "from": "human", "value": "How does immersion passively help with learning a language?" }, { "from": "gpt", "value": "There are a few reasons why immersion helps you learn a language without you actively trying:\n* 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.\n* 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.\n* 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.\n* 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." } ]
[ { "from": "human", "value": "I have a script, that does not exit when I want it to.\nAn example script with the same error is:\n```#!/bin/bash\nfunction bla() {\n return 1\n}\nbla || ( echo '1' ; exit 1 )\necho '2'\n```\nI would assume to see the output:\n```:~$ ./\n1\n:~$\n```\nBut I actually see:\n```:~$ ./\n1\n2\n:~$\n```\nDoes the ```()``` command chaining somehow create a scope? What is ```exit``` exiting out of, if not the script?" }, { "from": "gpt", "value": "```()``` 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.\nFrom bash manual:\n\n (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.\n { 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.\n\nIt'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:\n```echo $(exit)\ncat <(exit)\n```\n\nWhile 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:\n\n* command started in the background\n```exit &\n```\ndoesn't exit the current shell because (after ```man bash```)\n\n 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.\n\n* the pipeline\n```exit | echo foo\n```\nstill exits only from the subshell.\nHowever 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\n```exit | exit | exit\n```\ndoes basically nothing in bash, but exits from the zsh because of the last ```exit```.\n* ```coproc exit``` also runs ```exit``` in a subshell.\n" } ]
[ { "from": "human", "value": "Adding a new swap file. How to edit fstab to enable swap after reboot?" }, { "from": "gpt", "value": "These ares the steps to create a swap on a file:\n\n1. Create a large file e.g. with\n```sudo mkdir -p /var/cache/swap/ # create a directory that holds the swap file\nsudo dd if=/dev/zero of=/var/cache/swap/myswap bs=1M count=4096 # for 4 GByte\n```\nOf course any other method of creating a file of defined size would do. \n\n2. Announce swap to the system\n```sudo chmod 0600 /var/cache/swap/myswap # only root should have access\nsudo mkswap /var/cache/swap/myswap # format as swap\nsudo swapon /var/cache/swap/myswap # announce to system\n```\nInsert the following line in ```/etc/fstab``` for swap from the next boot:\n```/var/cache/swap/myswap none swap sw 0 0\n```\n\nNote: \n1. 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.\n2. You can not use a swap file for hibernation (see Ubuntu SwapFaq)\n3. 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.\n\nIn 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\n```sudo swapoff -a # for all\n```\nThen remove the swap entry from ```/etc/fstab``` or replace it with the new swap respectively." } ]
[ { "from": "human", "value": "\nHow do I add a validation to make sure the date string being passed to the method is in the ffg. format:\n```'YYYY-MM-DD'\n```\nif it's not, method should raise some sort of error" }, { "from": "gpt", "value": "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.\nAs an example:\n```>>> from dateutil.parser import parse\n>>> parse(\"2003-09-25\")\ndatetime.datetime(2003, 9, 25, 0, 0)\n```\nThis raises a ```ValueError``` if the date is not formatted correctly:\n```\nValueError: day is out of range for month\n```\n\n```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. \nIt also handles timezones if you need that.\nUpdate 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.\n\n```>>> parse('11/12/2001')\n>>> datetime.datetime(2001, 11, 12, 0, 0) # Nov 12\n>>> parse('11/12/2001', dayfirst=True)\n>>> datetime.datetime(2001, 12, 11, 0, 0) # Dec 11\n```" } ]
[ { "from": "human", "value": "When to use UICollectionView instead of UITableView?" }, { "from": "gpt", "value": "That depends on the requirements. How the application flows determines which type of UI to integrate into the application.\nPeople 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.\nWhen 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```:\n````-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath`\n```\nYou get the selected row instead of the item, so for creating grid or modified items, using ```UICollectionview``` is best.\nFor the listing details of each item, people use ```UITableView``` because it shows more info on each item.\nApple Docs:\nUICollectionView Class Reference\n\n 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.\n\nUITableView Class Reference\n\n 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. " } ]
[ { "from": "human", "value": "On my branch I had some files in .gitignore\nOn a different branch those files are not.\nI want to merge the different branch into mine, and I don't care if those files are no longer ignored or not.\nUnfortunately I get this: \n\n The following untracked working tree files would be overwritten by merge\n\nHow would I modify my pull command to overwrite those files, without me having to find, move or delete those files myself?" }, { "from": "gpt", "value": "Safely remove/overwrite only bothersome files\nWhen you want to ```merge```:\n```git checkout -f donor-branch # replace bothersome files with tracked versions\ngit checkout receiving-branch # tracked bothersome files disappear\ngit merge donor-branch # merge works\n```\nWhen you want to ```pull```:\n```git fetch\ngit checkout -f origin/mybranch # replace bothersome files with tracked versions\ngit checkout mybranch # tracked bothersome files disappear\ngit pull origin/mybranch # pull works\n```\nThat's all you need to know to use this. Below is an explanation.\n\nDetailed explanation\nThe Bothersome Files that we are going to remove:\n\n* exist in the donor branch (for ```git pull```: the upstream branch),\n* do not exist in the receiving branch,\n* and are blocking the merge because they are present and untracked in your working directory.\n\n```git merge -f``` and ```git pull -f``` do not exist, but ```git checkout -f``` does.\nWe will use ```git checkout -f``` + ```git checkout``` to track + remove the Bothersome Files, and then your merge can proceed normally.\nStep 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).\n```git checkout -f donor-branch\n```\nStep 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.\n```git checkout receiving-branch\n```\nStep 3. Now that the Bothersome Files are absent, merging in the donor branch will not overwrite any untracked files, so we get no errors.\n```git merge donor-branch\n```" } ]
[ { "from": "human", "value": "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. \nMy 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. " }, { "from": "gpt", "value": "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).\n\nIn 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.\n\nBut 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." } ]
[ { "from": "human", "value": "How do GPS receivers communicate with satellites?" }, { "from": "gpt", "value": "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!\n(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)\nThe 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.\nThis 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.\nNewer GNSS signals replace gold codes with newer techniques - like 'multiplexed binary offset carriers' - which perform better, but do basically the same thing." } ]
[ { "from": "human", "value": "Why is iceberg lettuce bad for rabbits?" }, { "from": "gpt", "value": "In short, iceberg lettuce is mostly water with little to no nutrient value. A rabbit can fill up on it (because of the bulk), but still need food because they didn't get enough calories, vitamins, minerals, etc.\nIf you look at the USDA's webpage on iceberg lettuce. You'll notice that water makes up just about 95% of the nutrients, leaving 5% to be divided up between every other nutrient. Protein is a little less than 1%, Carbohydrates less than 3%, and sugars less than 2%.\nMost importantly, you want to pay attention to the vitamin and calorie content. Iceberg lettuce has only 14 calories per 100 grams (2 calories or less in each leaf), and 18mg of calcium.\nOther effects to consider, is when fed straight from the fridge, lettuce will be cold and wet, both are conditions that can upset a pet's stomach.\nIn addition, since most rabbit breeders do not feed lettuce to their baby rabbits, it is an unfamiliar food and if the rabbit owner does not add lettuce to the diet gradually, it will cause stomach upset.\nFinally, it is often believed amoung rabbit breeders that\n\nRabbits should not eat some lettuces (such as iceberg) as they contain a substance called laudanum which can be harmful in large quantities.\n\nRSPCA: Rabbit Diet Myths\nBut this is disputed because\n\nLettuce does not contain laudanum. Edible lettuce does contain a chemical called lactucin which is a component of lactucarian. Lactucarian is the milky fluid found in some species of lettuce and occurs in much larger amounts in wild lettuce, Lactuca virosa.\nLactucarium has sedative and analgesic effects. It creates a sense of mild euphoria. The milky exudate resembles that of opium and it can also be reduced to a thick substance which can be smoked in the same way as opium. As a result of which it acquired the name ‘lettuce opium’.\nEdible lettuce, Lactuca sativa, does not even contain lactucarium although it does contain lactucin which is in lactucarium.\n\nLettuce for Rabbits and Guinea Pigs (note that rabbits and guinea pigs have different digestive systems, this link is included for the information on lettuce composition).\nIt is not known if lactucin turns into lactucarium during the digestive process in the rabbit, there are some accounts of rabbits appearing sedated after ingesting large quantities of lettuce. Regardless of the laudanum/lactucin status, there's no reason to feed iceberg because of the low nutrient value.\nThe House Rabbit Society's website has even more details on what foods are good for rabbits and why." } ]
[ { "from": "human", "value": "How do I open the JavaScript console in different browsers?" }, { "from": "gpt", "value": "Chrome\nOpening the “Console” panel of Chrome’s DevTools:\n\n* Windows and Linux: Ctrl + Shift + J\n* Mac OS: Cmd + Opt + J\n\nNote: 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. \n\nFirefox\nOpening the “Console” panel in Firefox’s Developer Tools:\n\n* Windows: Ctrl + Shift + K\n* Mac OS: Cmd + Opt + K\n\nNote: 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. \n\nInternet Explorer\nOpening the “Console” panel in Internet Explorer’s F12 Developer Tools:\n\n* F12, then click on the “Console” tab\n\nNote: 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. \n\nSafari\nNote: 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). \nOpening the “Console” panel in Safari’s Web Inspector:\n\n* Cmd + Opt + C\n\nNote: 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. \n\nOpera\n\n* Windows and Linux: Ctrl + Shift + I\n* Mac : ⌘+⌥+I\n" } ]
[ { "from": "human", "value": "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\n```/sbin/mount.vboxsf: mounting failed with the error: Protocol error\n```\nI have read so many solutions to this, but none seem to work. I have tried:\n\n* Using the mount.vboxsf syntax\n* Reinstalling VBox additions\n* Rebooting\n* Enabling and trying as root account\n\nI 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:\n```sudo mount -t vboxsf Test /mnt/test2\n```\nAny other ideas?" }, { "from": "gpt", "value": "In order to use shared folder functionality few prerequisites need to be met:\n\n* Make sure that Guest Additions are properly installed on the guest OS.\n* Users in a guest Ubuntu must be in the group ```vboxsf``` to be able to access shares.\n* Define a directory on the host that will be used in the virtual machine using the settings dialogue of Virtual Box.\n\nDepending on host or guest OS the following may also be needed:\n\n* Do not share personal folders like ```/home/username``` or ```My Documents```\n* Avoid special characters or empty spaces in the path to the shared folder, especially if the host or VM is a Windows machine\n* Use different names for share and mountpoint\n* Create a mountpoint on the guest OS (best in your HOME directory).\n\nTesting 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:\n```sudo mount -t vboxsf -o uid=1000,gid=1000 share /home/username/host\n```\nwhere the option -o makes sure that you will have access to the mount (that will otherwise be owned by root).\nFor further information on shared folders see also the Virtual Box User Manual.\nFiles or directories can also be shared over the network by using Samba on the host and the guest." } ]
[ { "from": "human", "value": "What does %~dp0 mean, and how does it work?\nI'd also like to know if it is a documented feature, or something prone to be deprecated." }, { "from": "gpt", "value": "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).\n\n> In addition, substitution of FOR variable references has been enhanced. You can now use the following optional\n syntax:\n```%~I - expands %I removing any surrounding quotes (\")\n%~fI - expands %I to a fully qualified path name\n%~dI - expands %I to a drive letter only\n%~pI - expands %I to a path only\n%~nI - expands %I to a file name only\n%~xI - expands %I to a file extension only\n%~sI - expanded path contains short names only\n%~aI - expands %I to file attributes of file\n%~tI - expands %I to date/time of file\n%~zI - expands %I to size of file\n%~$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\n```\n The modifiers can be combined to get compound results:\n```%~dpI - expands %I to a drive letter and path only\n%~nxI - expands %I to a file name and extension only\n%~fsI - expands %I to a full path name with short names only\n%~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.\n%~ftzaI - expands %I to a DIR like output line\n```\n 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.\n\nThere 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)." } ]
[ { "from": "human", "value": "Should a tester feel bad about finding too many defects/bugs in the product?" }, { "from": "gpt", "value": "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.\nA 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:\n\n* It has been caught before product release\n* It is pretty standard for a programmer fixing bugs daily\n* If you have to focus on programming it is hard also to focus on testing\n* A tester Always reports bugs\n* A regular user usually not (unless particularly angry or determined)\n* 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.\n\nLiterally a project for which bugs are not reported at least on a weekly basis:\n\n* Too simple project: no value every other company could easily create a better clone\n* Not much-used project: maybe there are bugs but no one incurred in them\n* Bad management: if there are no bugs it's time to move on further work (extra features or different projects).\n* 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\n* 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\n" } ]
[ { "from": "human", "value": "Millions of colors in the visible spectrum can be generated by mixing red, green and blue - the RGB color system. Is there a basic set of smells that, when mixed, can yield all, or nearly all detectable smells ?" }, { "from": "gpt", "value": "There are about 100 (Purves, 2001) to 400 (Zozulya et al., 2001) functional olfactory receptors in man. While the total tally of olfactory receptor genes exceeds 1000, more than half of them are inactive pseudogenes. The combined activity of the expressed functional receptors accounts for the number of distinct odors that can be discriminated by the human olfactory system, which is estimated to be about 10,000 (Purves, 2001).\nDifferent receptors are sensitive to subsets of chemicals that define a “tuning curve.” Depending on the particular olfactory receptor molecules they contain, some olfactory receptor neurons exhibit marked selectivity to particular chemical stimuli, whereas others are activated by a number of different odorant molecules. In addition, olfactory receptor neurons can exhibit different thresholds for a particular odorant. How these olfactory responses encode a specific odorant is a complex issue that is unlikely to be explained at the level of the primary neurons (Purves, 2001). \nSo in a way, the answer to your question is yes, as there are approximately 100 to 400 olfactory receptors. Just like the photoreceptors in the visual system, each sensory neuron in the olfactory epithelium in the nose expresses only a single receptor gene (Kimball). In the visual system for color vision there are just three (red, green and blue cones - RGB) types of sensory neurons, so it's a bit more complicated in olfaction.\nReferences\n- Purves et al, Neuroscience, 2nd ed. Sunderland (MA): Sinauer Associates; 2001\n- Zozulya et al., Genome Biol (2001); 2(6): research0018.1–0018.12\nSources\n- Kimball's Biology Pages" } ]
[ { "from": "human", "value": "Do you bleed to death after your penis is cut off?" }, { "from": "gpt", "value": "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. \nLeft to fend for himself, a healthy adult would almost certainly survive having his penis removed. With modern medical care, that becomes a certainty.\nCould 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.\nDownvoter, care to comment?" } ]
[ { "from": "human", "value": "In Swift, is there a clever way of using the higher order methods on Array to return the 5 first objects?\nThe 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```?" }, { "from": "gpt", "value": "With Swift 5, according to your needs, you may choose one of the 6 following Playground codes in order to solve your problem.\n\n#1. Using ```subscript(_:)``` subscript\n```let array = [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\"]\nlet arraySlice = array[..<5]\n//let arraySlice = array[0..<5] // also works\n//let arraySlice = array[0...4] // also works\n//let arraySlice = array[...4] // also works\nlet newArray = Array(arraySlice)\nprint(newArray) // prints: [\"A\", \"B\", \"C\", \"D\", \"E\"]\n```\n\n#2. Using ```prefix(_:)``` method\nComplexity: 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.\n```let array = [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\"]\nlet arraySlice = array.prefix(5)\nlet newArray = Array(arraySlice)\nprint(newArray) // prints: [\"A\", \"B\", \"C\", \"D\", \"E\"]\n```\nApple states for ```prefix(_:)```:\n\n If the maximum length exceeds the number of elements in the collection, the result contains all the elements in the collection.\n\n\n#3. Using ```prefix(upTo:)``` method\nComplexity: O(1)\n```let array = [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\"]\nlet arraySlice = array.prefix(upTo: 5)\nlet newArray = Array(arraySlice)\nprint(newArray) // prints: [\"A\", \"B\", \"C\", \"D\", \"E\"]\n```\nApple states for ```prefix(upTo:)```:\n\n 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:)```.\n\n\n#4. Using ```prefix(through:)``` method\n```let array = [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\"]\nlet arraySlice = array.prefix(through: 4)\nlet newArray = Array(arraySlice)\nprint(newArray) // prints: [\"A\", \"B\", \"C\", \"D\", \"E\"]\n```\n\n#5. Using ```removeSubrange(_:)``` method\nComplexity: O(n), where n is the length of the collection.\n```var array = [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\"]\narray.removeSubrange(5...)\nprint(array) // prints: [\"A\", \"B\", \"C\", \"D\", \"E\"]\n```\n\n#6. Using ```dropLast(_:)``` method\nComplexity: O(1) if the collection conforms to ```RandomAccessCollection```; otherwise, O(k), where k is the number of elements to drop.\n```let array = [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\"]\nlet distance = array.distance(from: 5, to: array.endIndex)\nlet arraySlice = array.dropLast(distance)\nlet newArray = Array(arraySlice)\nprint(newArray) // prints: [\"A\", \"B\", \"C\", \"D\", \"E\"]\n```" } ]
[ { "from": "human", "value": "What's the simplest way to get an environment variable from a docker container that has not been declared in the Dockerfile?\nFor instance, an environment variable that has been set through some ```docker exec container /bin/bash``` session?\nI can do ```docker exec container env | grep ENV_VAR```, but I would prefer something that just returns the value.\nI'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.\nThanks." }, { "from": "gpt", "value": "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.\nExample #1. Output a list of space-separated environment variables in the specified container:\n```docker inspect -f \\\n '{{range $index, $value := .Config.Env}}{{$value}} {{end}}' container_name\n```\nthe output will look like this:\n```ENV_VAR1=value1 ENV_VAR2=value2 ENV_VAR3=value3\n```\nExample #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:\n```docker inspect -f \\\n '{{range $index, $value := .Config.Env}}{{println $value}}{{end}}' \\\n container_name | grep MYSQL_\n```\nwill output:\n```MYSQL_PASSWORD=secret\nMYSQL_ROOT_PASSWORD=supersecret\nMYSQL_USER=demo\nMYSQL_DATABASE=demodb\nMYSQL_MAJOR=5.5\nMYSQL_VERSION=5.5.52\n```\nExample #3. Let's modify the example above to get a bash friendly output which can be directly used in your scripts:\n```docker inspect -f \\\n '{{range $index, $value := .Config.Env}}export {{$value}}{{println}}{{end}}' \\\n container_name | grep MYSQL\n```\nwill output:\n```export MYSQL_PASSWORD=secret\nexport MYSQL_ROOT_PASSWORD=supersecret\nexport MYSQL_USER=demo\nexport MYSQL_DATABASE=demodb\nexport MYSQL_MAJOR=5.5\nexport MYSQL_VERSION=5.5.52\n```\nIf you want to dive deeper, then go to Go’s text/template package documentation with all the details of the format." } ]
[ { "from": "human", "value": "I am confused about the use cases for both ```InputStream``` and ```OutputStream```.\nPlease include a snippet of code to go along with your explanation." }, { "from": "gpt", "value": "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.\nFor example, you can write primitive data to a file:\n```File file = new File(\"C:/text.bin\");\nfile.createNewFile();\nDataOutputStream stream = new DataOutputStream(new FileOutputStream(file));\nstream.writeBoolean(true);\nstream.writeInt(1234);\nstream.close();\n```\nTo read the written contents:\n```File file = new File(\"C:/text.bin\");\nDataInputStream stream = new DataInputStream(new FileInputStream(file));\nboolean isTrue = stream.readBoolean();\nint value = stream.readInt();\nstream.close();\nSystem.out.printlin(isTrue + \" \" + value);\n```\nYou can use other types of streams to enhance the reading/writing. For example, you can introduce a buffer for efficiency:\n```DataInputStream stream = new DataInputStream(\n new BufferedInputStream(new FileInputStream(file)));\n```\nYou can write other data such as objects:\n```MyClass myObject = new MyClass(); // MyClass have to implement Serializable\nObjectOutputStream stream = new ObjectOutputStream(\n new FileOutputStream(\"C:/text.obj\"));\nstream.writeObject(myObject);\nstream.close();\n```\nYou can read from other different input sources:\n```byte[] test = new byte[] {0, 0, 1, 0, 0, 0, 1, 1, 8, 9};\nDataInputStream stream = new DataInputStream(new ByteArrayInputStream(test));\nint value0 = stream.readInt();\nint value1 = stream.readInt();\nbyte value2 = stream.readByte();\nbyte value3 = stream.readByte();\nstream.close();\nSystem.out.println(value0 + \" \" + value1 + \" \" + value2 + \" \" + value3);\n```\nFor 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)." } ]
[ { "from": "human", "value": "What is the difference between:\n```npm install [package_name]\n```\nand:\n```npm install [package_name] --save\n```\nand:\n```npm install [package_name] --save-dev\n```\nWhat does this mean? And what is really the effect of ```--save``` and ```-dev``` keywords?" }, { "from": "gpt", "value": "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...\nLet'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\n```npm install moment --save\n```\nThis would create a new value in your package.json\n```&quot;dependencies&quot;: {\n ...\n &quot;moment&quot;: &quot;^2.17.1&quot;\n}\n```\nWhen 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\n```npm install jasmine-core --save-dev\nnpm install karma --save-dev\n```\nThis would also create a new value in your package.json\n```&quot;devDependencies&quot;: {\n ...\n &quot;jasmine-core&quot;: &quot;^2.5.2&quot;,\n &quot;karma&quot;: &quot;^1.4.1&quot;,\n}\n```\nYou 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.\nTaken directly from NPM docs docs#dependencies\n\n> Dependencies \n> 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.\n\nEven in the docs, it asks you to use ```--save-dev``` for modules such as test harnesses." } ]
[ { "from": "human", "value": "pod install -bash: pod: command not found" }, { "from": "gpt", "value": "Please follow the following steps to install Pod:\n\n1. Open terminal and type:\n```sudo gem install cocoapods\n```\nGem will get installed in Ruby inside the System library. Or try on 10.11 Mac OSX El Capitan, type:\n```sudo gem install -n /usr/local/bin cocoapods\n```\nIf there is an error &quot;activesupport requires Ruby version >= 2.xx&quot;, then install the latest active support first by typing in the terminal.\n```sudo gem install activesupport -v 4.2.6\n```\n2. 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:\n```pod setup\n```\nAnd 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:\n```pod setup --verbose\n```\n3. Once done it will output &quot;Setup Complete&quot;, and you can create your XCode project and save it.\n4. Then in a terminal cd to &quot;your XCode project root directory&quot; (where your .xcodeproj file resides) and type:\n```pod init\n```\n5. Then open your project's podfile by typing in terminal:\n```open -a Xcode Podfile\n```\n6. 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\n```/****** These are Third party pods names ******/\npod 'OpenSSL-Universal'\npod 'IQKeyboardManager'\npod 'FTPopOverMenu'\npod 'TYMActivityIndicatorView'\npod 'SCSkypeActivityIndicatorView'\npod 'Google/SignIn'\npod 'UPStackMenu'\n```\n(this is For example of adding library to your project).\nWhen you are done editing the podfile, save it and close XCode.\n7. Then install pods into your project by typing in terminal:\n```pod install\n```\nDepending 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;" } ]
[ { "from": "human", "value": "I read in the Essential C# 3.0 and .NET 3.5 book that:\n\n GetHashCode()’s returns over the life of a particular object should be\n constant (the same value), even if the object’s data changes. In many\n cases, you should cache the method return to enforce this.\n\nIs this a valid guideline?\nI have tried a couple built-in types in .NET and they didn't behave like this." }, { "from": "gpt", "value": "The answer is mostly, it is a valid guideline, but perhaps not a valid rule. It also doesn't tell the whole story.\n\nThe 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.\nFor 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.\n\nA 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." } ]
[ { "from": "human", "value": "Especially in blitz or bullet games, it is possible that a player makes an illegal move, for example castles through check. \n\n* If the opponent does notice the illegal move, then as far as I know the first player is obliged to make a legal move with the same piece, if one exists. What if there are no legal moves? \n* What if the opponent, being in time pressure, doesn't notice the illegal move and makes a move. What happens after they realize that? Does the person who made the illegal move forfeit? Or is the whole game cancelled?\n\nAre there any standard rules for these kinds of situations?" }, { "from": "gpt", "value": "This only really applies to over the board games (since online chess servers prevent illegal moves).\nIn a standard time control game, under USCF rules, when the illegal move is noticed by one of the players, a few things happen. First, the illegal move must have been made within the last 10 moves. If not, then the current position stands, and play continues. Assuming that the move is recent, the position is restored to the position immediately before the illegal move.\nThen, the player that made the illegal move now must make a legal move with the same piece (if one exists). If there are no legal moves, then the player is free to make any move. This is due to the touch move rule. Finally, if the offending player has pressed the clock, a two minute &quot;bonus&quot; is added to the opponent's clock to compensate them for any time lost and to penalize the offending player.\nHere is the relevant passage from the USCF rulebook:\n\n11A. Illegal move during last ten moves. If, during a game, it is found that one of either player's last ten moves was illegal, the position shall be reinstated to what it was before the illegal move. The game shall then continue by applying Rule 10, The Touched Piece, to the move replacing the illegal move. If the position cannot be reinstated, then the illegal move shall stand. Move counters on clocks that have them may by readjusted.\n11D. Illegal move. If, a player completes an illegal move by pressing the clock, in addition to the usual obligation to make a legal move with the touched piece if possible, the standard penalty specified in rule 1C2a applies (i.e. two minutes added to the opponent's clock).\n\nIn blitz chess, the rules are different. According to the WBCA (World Blitz Chess Association) rules, a player who makes an illegal move loses the game instantly. This rule is frequently enforced in casual games too. The most common way that this occurs is that one player doesn't notice that they are in check and makes a move that doesn't get out of check. Then the checking player simply captures the king and claims a victory.\nBecause blitz is a much faster pace game, the illegal move must be noticed within two moves. If it is not, then the current position stands and play continues.\nAt no point is the game cancelled due to an illegal move. Pretty much once a game starts and both players make a move, a result of win, loss, or draw will be recorded." } ]
[ { "from": "human", "value": "How to set button click effect in Android?" }, { "from": "gpt", "value": "It is simpler when you have a lot of image buttons, and you don't want to write xml-s for every button.\nKotlin Version:\n```fun buttonEffect(button: View) {\n button.setOnTouchListener { v, event ->\n when (event.action) {\n MotionEvent.ACTION_DOWN -> {\n v.background.setColorFilter(-0x1f0b8adf, PorterDuff.Mode.SRC_ATOP)\n v.invalidate()\n }\n MotionEvent.ACTION_UP -> {\n v.background.clearColorFilter()\n v.invalidate()\n }\n }\n false\n }\n}\n```\nJava Version:\n```public static void buttonEffect(View button){\n button.setOnTouchListener(new OnTouchListener() {\n public boolean onTouch(View v, MotionEvent event) {\n switch (event.getAction()) {\n case MotionEvent.ACTION_DOWN: {\n v.getBackground().setColorFilter(0xe0f47521,PorterDuff.Mode.SRC_ATOP);\n v.invalidate();\n break;\n }\n case MotionEvent.ACTION_UP: {\n v.getBackground().clearColorFilter();\n v.invalidate();\n break;\n }\n }\n return false;\n }\n });\n}\n```" } ]