instruction stringlengths 17 7.84k | response stringlengths 15 13.7k |
|---|---|
The year is 2109 C.E my friends and I were caught in a space disaster when the spacecraft we're in broke apart during a daring escape from a patrolling spacecraft. We stole an antique cellphone (from 1999, in good working condition) from a space museum but our escape was interrupted and fortunately we managed to get in... | Assets
* 1 obsolete piece of short range comms kit requiring a battery you probably can't charge
* 1 slightly malfunctioning escape pod with up to date comms that isn't working but you're still alive
Current standards say the Mayday should be broadcast on VHF channel 16 (156.8 MHz). A 1999 phone, probably on 2g would... |
Often I want to just point the camera to an object or a specific area in my scene to get an idea of how it'll look in the render. What's the most painless hassle-free way to do this in blender?
A quick search on the blender wiki does not lend itself to easy look-up due to all the noise in the search result.
This questi... | Situation 1: You're not looking through the camera yet
* Fly Mode: Shift + F or the standard Viewport Navigation
* Set Camera to View: Ctrl + Alt + Numpad 0
Situation 2: You're already looking through the camera via Numpad 0
* Select the camera: Right Mouse Button
* Grab: G & optionally...
* Lock the grab to a loca... |
What are the general tactics of Krav Maga as opposed to Systema?
For instance, the tactics of Silat are to hurt the other person so badly they can't hurt back. Another example would be that the tactics of boxing would be to knock out the other person first using only punches. So, as far as I know, the goal of Systema ... | At first glance Krav Maga and Systema seem to be very similar in that they are both very unconventional, no-rules, practical self-defence, martial arts (although Krav isn't technically a martial art) which are no holds barred and generally formless.
However...
Krav Maga is basically a very raw, dangerous situation sur... |
I understand that unlocking the bootloader will wipe my Android phone, but have been looking around for why. Seems to be by design, but what is the reasoning for that design? Is it some security concern, some obscure technical reason, or just for lulz? I'm looking for something solid to chew on here, something more ... | It's a security concern. The Android documentation doesn't provide a lot of elaboration, stating simply:
The procedure must be confirmed on-screen, and deletes the user data for privacy reasons.
However, the privacy concern is relatively straightforward to extrapolate. Once the bootloader is unlocked, the device ca... |
The original IBM PC and later variants used an Intel 8253 or 8254 as a sound chip. Why did users add sound cards such as the Adlib or Sound Blaster. I remember voice output with programs like telephone answering programs. The sound was wimpy but I attributed most of the quality to speaker size.
What was lacking with th... | > The original IBM PC and later variants used an Intel 8253 or 8254 as a sound chip.
The 8253 is a timer circuit, containing three timers able to generate timed interrupts or square-wave output with programmed frequencies. On the PC the third timer's output is, via an amplifier, connected to a simple speaker.
As said... |
According to the sources I have found, a lambda expression is essentially implemented by the compiler creating a class with overloaded function call operator and the referenced variables as members. This suggests that the size of lambda expressions varies, and given enough references variables that size can be arbitrar... | The implementation of ```std::function``` can differ from one implementation to another, but the core idea is that it uses type-erasure. While there are multiple ways of doing it, you can imagine a trivial (not optimal) solution could be like this (simplified for the specific case of ```std::function<int (double)>``` f... |
So, I'm on vacation in Utah, and so I attended an LDS service. In the morning, I heard a reading from one of the Presidents of the church during the "Quorum of the Elders," then went to Sunday School, and finally witnessed the Sacrement of the bread and water. (I guess it makes sense there was no wine, but it did make ... | Mormon services are a bit different, as you discovered. In the United States, there is generally a block of 3 meetings back-to-back including a sunday school, a mens' and women's time for instruction, and a sacrament meeting where the general congregation meets together. It sounds like the first meeting you attended wa... |
A partir de un String, ```"123-654321"```, lo que deseo es dividirlo en dos Strings:
```string1=123
string2=654321
``` | Tres formas diferentes de hacerlo:
1. Utilizando la función ```String.split()``` :
``` String str = "123-654321";
String[] parts = str.split("-");
```
Esta solución utiliza expresiones regulares, así que no es lo más eficiente si no estas trabajando con ellas.
2. Utilizando la clase ```StringTokenizer``` :
```static ... |
What’s the difference between ```\n``` (newline) and ```\r``` (carriage return)?
In particular, are there any practical differences between ```\n``` and ```\r```? Are there places where one should be used instead of the other? | In terms of ascii code, it's 3 -- since they're 10 and 13 respectively.
But seriously, there are many differences:
* in Unix and all Unix-like systems, ```\n``` is the code for end-of-line, ```\r``` means nothing special
* as a consequence, in C and most languages that somehow copy it (even remotely), ```\n``` is the ... |
Assume that I am a programmer and I have an NP-complete problem that I need to solve it. What methods are available to deal with NPC problems? Is there a survey or something similar on this topic? | There are a number of well-studied strategies; which is best in your application depends on circumstance.
* Improve worst case runtime
Using problem-specific insight, you can often improve the naive algorithm. For instance, there are $O(c^n)$ algorithms for Vertex Cover with $c huge improvement over the naive $\Omega(... |
I have a new SPA with a stateless authentication model using JWT. I am often asked to refer OAuth for authentication flows like asking me to send 'Bearer tokens' for every request instead of a simple token header but I do think that OAuth is a lot more complex than a simple JWT based authentication. What are the main d... | TL;DR If you have very simple scenarios, like a single client application, a single API then it might not pay off to go OAuth 2.0. On the other hand, if there are lots of different clients (browser-based, native mobile, server-side, etc) then sticking to OAuth 2.0 rules might make it more manageable than trying to roll... |
Gostaria de saber se existe alguma forma simples de realizar um upload de arquivos via AJAX + JSON.
Se houver, qual seria? | Você pode fazer uploads de arquivos utilizando o método ```POST``` porém deve incluir o FormData com a propriedade ```enctype``` definida como ```multipart/form-data``` para que seus arquivos sejam enviados na requisição.
Contudo, a formatação do envio não vai ser um JSON, mas sim no ```enctype``` que você definir no s... |
Did the ancients or other pre-industrial civilisations engage in unsustainable practices? | Most ancient agricultural practices deplete soil to some degree, but are just fine when population does not exceed certain limits. There are some examples of ancient cultures exhausting natural resources available to them - Pitcairn Island Polynesians, Ancient Puebloans (Anasazi). It's the cause of the semi-nomadic way... |
When reading my Bible, I've noticed Joesph's name listed in both the Old and New Testaments; is it the same person or is there more than one Joseph in the Bible? | There are 3 distinct (fairly) well-known Josephs in the Bible, firstly in the Old Testament (mainly):
* Joseph the son of Jacob/Israel (aka The Patriarch Joseph). This Joseph is actually referred to in a few select places in the New Testament: John 4:5; Acts 7:9-18; Hebrews 11:21-22 & Revelation 7:8.
However, it's mo... |
Para que serve o "with" no Python? | Ele é usado para garantir finalização de recursos adquiridos.
Um arquivo, por exemplo é aberto. Quem garante que ele será fechado? Mesmo que você coloque no código de forma explícita que ele deve ser fechado, se ocorrer uma exceção, o código sai de escopo sem executar o resto do código que está em escopo, ele pula o f... |
The question bothers me since February 2022. Why (legally) are Russian combatants in Ukraine considered soldiers (thus POWs when captured) rather than terrorists?
* There is no formal declaration of war.
* They are members an organization (Russian military) that commits acts of terrors to civilian population in clea... | The third Geneva convention says in its second article (emphasis added):
> the present Convention shall apply to all cases of declared war or of any other armed conflict which may arise between two or more of the High Contracting Parties, even if the state of war is not recognized by one of them.
> The Convention shall... |
Are there any advantages while backpacking to hike during the night and sleep during the day? | There are several reasons, though not all of them would apply for one's usual holiday trip.
1. Remaining unseen: Obviously, during night its dark and this gives you a fair bit of cover if you want to remain unseen. This reason for traveling at night is common for many hunters in the animal kingdom (and sometimes also ... |
I have been cautioned against blending:
* Traditional fantasy elements
Such as magic systems and exotic, less plausible creatures (on a scientific level - magic tends to explain away these beasts)
* Traditional sci-fi elements
Such as advanced technology and civilizations amidst the stars.
I have taken it upon myse... | Any sufficiently advanced technology is indistinguishable from magic.
- Arthur C Clarke
There's a reason that science fiction and fantasy are frequently shelved together - separating the two is usually a fools errand.
The Dragonriders of Pern features a preindustrial society where flying, firebreathing, teleporti... |
Why are prions in animal diets not destroyed by the digestive system? | Proteases are enzymes in your digestive system that help break down food, acting like molecular-sized scissors that cut up proteins.
Proteases have clefts, or subpockets, into which proteins fit, where the substrate (protein) gets cut.
Infectious or pathogenic prions are resistant to proteases, because of their three... |
How slicing in Python works? Please include references where appropriate. | The syntax is:
```
a[start:stop] # items start through stop-1
a[start:] # items start through the rest of the array
a[:stop] # items from the beginning through stop-1
a[:] # a copy of the whole array
```
There is also the `step` value, which can be used with any of the above:
```
a[start:stop:st... |
I am writing a story where a species undergoes devolution. Is there any scientific or plausible way to do this? The process can be instantaneous or may take ages, I do not mind which as I need to weigh my options at this stage.
To be clear, the devolution I am thinking of is like taking a human being then devolving hi... | Devolution doesn't really ever occur, organisms simply adapt to best suit their environment over time. A good example is cave dwelling Troglodyte type species that have lost the ability to see. They haven't actually devolved to not have eyes, they simply did not need them and evolved to save valuable energy and nutrien... |
I've used GEDCOM to transfer data between desktop software and websites, but it all seems a bit old hat. Is there anything better that will mangle* my data less.
* For example, GEDCOM can lose some data where the two ends of the system understand a concept which GEDCOM does not have a field for. | GEDCOM is the defacto standard for exchanging genealogical data. There are some problems with GEDCOM.
* It is not rich enough to hold all the types of information that different vendor systems manage internally. So exporting GEDCOM from one system may lose information that that system actually holds. Though see point ... |
Is it ever possible that ```(a== 1 && a ==2 && a==3)``` could evaluate to true in JavaScript? | If you take advantage of how == works, you could simply create an object with a custom ```toString``` (or ```valueOf```) function that changes what it returns each time it is used such that it satisfies all three conditions.
```
const a = {
i: 1,
toString: function () {
return a.i++;
}
}
if(a == 1 && a == 2 ... |
Gostaria de saber qual é a real diferença entre o ```String``` (s maiúsculo) e o ```string``` (s minúsculo).
Aparentemente os dois têm os mesmos objetivos, porém qual é "melhor" para ser utilizado? | Já foi dito que ```string``` é apenas um alias para o tipo ```String```.
Para deixar claro, não há diferença em performance ou forma como o código é gerado. Há exatamente zero diferença no tratamento de ambas. Elas podem fazer as mesmas coisas, e todos os membros estão disponíveis em qualquer um deles, afinal assim se ... |
Assume an environment with a puppet-managed cluster of different servers - various hardware, software, operating systems, virtual/dedicated, etc.
Would you choose meaningful hostnames (mysqlmaster01..99, mysqlslave001..999, vpnprimary, vpnbackup, etc.) or would you prefer meaningless hostnames such as characters from a... | This largely comes down to whether your servers are ```pets``` or ```livestock```.
Pets get individual names. They're distinct from each other, and we care about those differences. When one gets sick, we usually try to nurse it back to health. Traditionally, servers have been pets.
Livestock get numbers. They're most... |
What does it mean for an album to be remastered? | Mastering is a separate art from recording or mixing. According to the Wikipedia article, the principle processes of mastering are:
* Editing minor flaws.
* Applying noise reduction to eliminate clicks, dropouts, hum and hiss.
* Adjusting stereo width.
* Adding ambience.
* Equalize audio across tracks for the purpose ... |
What's the best way to iterate over the items in a ```HashMap```? | Extracted from the reference How to Iterate Over a Map in Java:
There are several ways of iterating over a ```Map``` in Java. Let's go over the most common methods and review their advantages and disadvantages. Since all maps in Java implement the Map interface, the following techniques will work for any map implementa... |
Say I have a file ```/templates/apple``` and I want to
* put it in two different places and then
* remove the original.
So, ```/templates/apple``` will be copied to ```/templates/used``` AND ```/templates/inuse```
and then after that I’d like to remove the original.
Is ```cp``` the best way to do this, followed by ``... | You are using ```|``` (pipe) to direct the output of a command into another command. What you are looking for is ```&&``` operator to execute the next command only if the previous one succeeded:
```cp /templates/apple /templates/used && cp /templates/apple /templates/inuse && rm /templates/apple
```
Or
```cp /template... |
When are Decision Diagrams the right way to model and solve a problem? | Decision diagrams (DDs) are most effective when they can compactly represent a large (perhaps exponential) set of solutions. This is done by merging equivalent states in each layer. To make decision diagrams scalable, we can use relaxed decision diagrams which allow merging nodes that are not necessarily equivalent. Re... |
Essentially, I have a protagonist who I set up as a 'main' good guy in one of my series. However, in my final series, I intend to make him turn to the dark side and oppose my other protagonists (from my other series). It's clear in his series that the protagonist-turned-antagonist is very devious, and he has had hostil... | Sounds like a great idea!
Seriously though: the antagonist is the single most important character to any plot. The very best antagonists have motivations and feelings that readers can understand and empathize with. A former protagonist as an antagonist sounds really good. Both the reader and the author should be in fo... |
I'd never heard of anycast until a few seconds ago when I read "What are some cool or useful server/networking tricks?".
The wikipedia "Anycast" article on it is quite formal and doesn't really evoke a mental picture of how it would be used.
Can someone explain in a few informal sentences what "anycast" is, how you con... | Anycast is networking technique where the same IP prefix is advertised from multiple locations. The network then decides which location to route a user request to, based on routing protocol costs and possibly the 'health' of the advertising servers.
There are several benefits to anycast. First, in steady state, users ... |
$A$ and $B$ are $n \times n$ matrices and $v$ is a vector with $n$ elements. $Av$ has $\approx 2n^2$ flops and $A+B$ has $n^2$ flops. Following this logic, $(A+B)v$ should be faster than $Av+Bv$.
Yet, when I run the following code in matlab
```A = rand(2000,2000);
B = rand(2000,2000);
v = rand(2000,1);
tic
D=zeros(size... | Except for code which does a significant number of floating-point operations on data that are held in cache, most floating-point intensive code is performance limited by memory bandwidth and cache capacity rather than by flops.
$v$ and the products $Av$ and $Bv$ are all vectors of length 2000 (16K bytes in double preci... |
I came across a piece of code ```void *p = &&abc;```. What is the significance of ```&&``` here?
I know about rvalue references but I think ```&&``` used in this context is different. What does ```&&``` indicate in ```void *p = &&abc;``` ? | ## How to find it out
That's the address of a label and it's a feature specific to GCC.
```int main(void) {
void* startp;
s:
startp = &&s;
printf("the assignment above starts at address %p\n", startp);
return 0;
}
```
You could have figured it out yourself by testing:
```int main(void) {
... |
When I execute "```python```" from the terminal with no arguments it brings up the Python interactive shell.
When I execute "```cat | python```" from the terminal it doesn't launch the interactive mode. Somehow, without getting any input, it has detected that it is connected to a pipe.
How would I do a similar detectio... | You can use ```isatty```:
```
#include <stdio.h>
#include <io.h>
...
if (isatty(fileno(stdin)))
printf( "stdin is a terminal\n" );
else
printf( "stdin is a file or a pipe\n");
```
On windows they're prefixed with underscores: ```_isatty```, ```_fileno```. |
"The video of Pythom Space's first rocket test has raised a few eyebrows
The video prompted hundreds of replies on Twitter, including some from rather horrified rocket scientists. "We knew better as untrained college students," said Jordan Noone, the co-founder of Relativity Space.
Pythom “Micro jump”
What ... | The easy-to-spot stuff:
* (assumed) Improper transportation of hazardous materials. Both white fuming nitric acid and furfuryl alcohol are considered hazardous materials; none of the vehicles in the video appears to have a hazmat placard, the rocket is not an approved hazmat container, and the fuel containers seen in... |
When should I use wp_register_script() with wp_enqueue_script() vs just wp_enqueue_script()? | The ```wp_register_script()``` Codex page literally says:
A safe way of registering javascripts in WordPress for later use with ```wp_enqueue_script()```.
This means, if you want to register your scripts, but not directly load them in your pages, you can register the files once, and then load them when you need the... |
Prove that the union of countably many countable sets is countable. | Let's start with a quick review of "countable". A set is countable if we can set up a 1-1 correspondence between the set and the natural numbers. As an example, let's take $\mathbb{Z}$, which consists of all the integers. Is $\mathbb Z$ countable?
It may seem uncountable if you pick a naive correspondence, say $1 \map... |
Você encontra na internet a afirmação que Singletons são ruins. Isto é verdade? Por quê?
O problema seria generalizado para quaisquer objetos com instância única? Ou para qualquer coisa que tenha estado global?
Se é tão ruim, pra que foi inventado? Ou seja, que problema ele queria resolver?
Quais os problemas que terei... | Muito da polêmica ocorre pela falta de uma contextualização. Não vejo nada que desabone o padrão Sigleton quando usado no contexto correto. Sim, ele pode causar muito mal, assim como qualquer padrão de projeto aplicado indevidamente sem análise do impacto e dos efeitos colaterais.
###Porque não usar
* Acoplamento. Ao ... |
The construction of Solomon's temple includes a piece of furnishing described in 1 Kings 7:23 (ESV):
Then he made the sea of cast metal. It was round, ten cubits from brim to brim, and five cubits high, and a line of thirty cubits measured its circumference.
So if the ```diameter = 10``` cubits and the ```circumfer... | To start with, compare the circle the diameter we're given would make with the circle the circumference we're given would make:
Since a circumference is π times the diameter, a 'pure' circle of 10 cubits in diameter as we describe the sea as having would be 10π cubits in circumference, or roughly 31.4 cubits.
Now, si... |
With PHP 7.2, ```each``` is deprecated. The documentation says:
Warning This function has been DEPRECATED as of PHP 7.2.0. Relying on this function is highly discouraged.
How can I update my code to avoid using it? Here are some examples:
*
```$ar = $o->me;
reset($ar);
list($typ, $val) = each($ar);
```
*
```$out ... |
* For your first two example cases, you could use ```key()``` and ```current()``` to assign the values you need.
```$ar = $o->me; // reset isn't necessary, since you just created the array
$typ = key($ar);
$val = current($ar);
```
*
```$out = array('me' => array(), 'mytype' => 2, '_php_class' => null);
$expected =... |
Can someone please give an explanation of different egg preparations? | Sure, here are different preparations of eggs:
1. Fried Eggs:
* Sunny Side Up -- Not flipped, unbroken yolk. The top of the egg is just barely set.
* Basted -- Sunny Side Up, hot fat spooned over until the white surrounding the yolk is opaque.
* Over Easy / lite -- Flipped, whites fully cooked, unbroken yolk, yolk r... |
In regards to Error handling in PHP -- As far I know there are 3 styles:
* ```die()```or ```exit()``` style:
```$con = mysql_connect("localhost","root","password");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
```
* ```throw Exception``` style:
``` if (!function_exists('curl_init')) {
throw new Ex... | The first one should never be used in production code, since it's transporting information irrelevant to end-users (a user can't do anything about "Cannot connect to database").
You throw Exceptions if you know that at a certain critical code point, your application can fail and you want your code to recover across mu... |
How do I change the author and committer name/email for multiple commits? | Here is the solution, but be careful if you have a multi-user repository - this will change all commits to have the same (new) author and committer.
```
git filter-branch -f --env-filter "
GIT_AUTHOR_NAME='Newname'
GIT_AUTHOR_EMAIL='new@email'
GIT_COMMITTER_NAME='Newname'
GIT_COMMITTER_EMAIL='new@email'... |
This summer I will be taking a rather inherently dangerous multi-day hike by myself. I was considering buying a flare gun since I will be out of cellular range unless there is something more modern and equally reliable. Any suggestions? | In increasing order of complexity and price you have,
* Personal Locator Beacons
Personal locator beacons are high-powered (typically, 5 watts) devices designed primarily to send out a personalized emergency distress signal. They generally require an open view of the sky to transmit successfully.
* Satellite Messe... |
In D&D, how many attacks can a fighter with two-weapon fighting make at 5th level? | Answer: 3 attacks on your turn (if you don't use Action Surge). (It could go up to five with Action Surge, though.)
The Two-Weapon Fighting rule states (PHB, page 195):
>When you take the Attack action and attack with a light melee weapon that you’re holding in one hand, you can use a bonus action to attack with a di... |
Consider the following code:
```avgDists = np.array([1, 8, 6, 9, 4])
ids = avgDists.argsort()[:n]
```
This gives me indices of the ```n``` smallest elements. Is it possible to use this same ```argsort``` in descending order to get the indices of ```n``` highest elements? | If you negate an array, the lowest elements become the highest elements and vice-versa. Therefore, the indices of the `n` highest elements are:
```
(-avgDists).argsort()[:n]
```
Another way to reason about this, as mentioned in the comments, is to observe that the big elements are coming last in the argsort. So, you ca... |
Relationship between SVD and PCA. How to use SVD to perform PCA? | Let the real values data matrix $\mathbf X$ be of $n \times p$ size, where $n$ is the number of samples and $p$ is the number of variables. Let us assume that it is centered, i.e. column means have been subtracted and are now equal to zero.
Then the $p \times p$ covariance matrix $\mathbf C$ is given by $\mathbf C = \... |
What is the English term for when someone thinks they are doing something nice for you but it ends up making things worse. EX: Someone buys you an elephant -- nice gesture and cool! But now you have to take care of it, and it becomes a burden on you. | In fact, the English expression for a burdensome gift is literally white elephant:
> a thing that is useless and no longer needed, although it may have cost a lot of money [OALD]
So-called white elephants, or albino elephants, are found in many parts of South and Southeast Asia. In Buddhist countries they may be vene... |
Why did the NES not allow rotated sprites? | For each sprite displayed on a scanline, the hardware fetches two bytes from memory, and then clocks the pixels out one by one. The sprite is eight pixels wide, and each pixel is two bits, which is why it's two memory accesses per sprite per scanline. You can imagine that this arrangement just needs a couple of shift r... |
I want to merge two dictionaries into a new dictionary.
```
x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z = merge(x, y)
>>> z
{'a': 1, 'b': 3, 'c': 4}
``` | Here is what you can do for the case you described:
```
z = dict(list(x.items()) + list(y.items()))
```
This will, as you want it, put the final dict in ```z```, and make the value for key ```b``` be properly overridden by the second (```y```) dict's value:
```>>> x = {'a': 1, 'b': 2}
>>> y = {'b': 1... |
There are many "standards" for the JSON content type:
application/json
application/x-javascript
text/javascript
text/x-javascript
text/x-json
Which one do I use, and where? I assume security and browser support issues are a factor. | According to RFC 4627:
The MIME media type for JSON text is application/json. The default encoding is UTF-8.
For JSON text, you should use:
```
application/json
```
For JSONP (runnable JavaScript) with callback, you should use:
```
application/javascript
``` |
What's the goal of Minecraft and what can users achieve in this world? | The thing about Minecraft is, unlike most games you set your own goals. Here's a list of common (and uncommon!) things people have done with Minecraft:
* Building a massive structure
* Recreating real-world objects
* Survival (Deleting map upon dying)
* Making amusing videos
* Creating an adventure map for others to p... |
If I have sampled a signal using proper sampling methods (Nyquist, filtering, etc) how do I relate the length of my FFT to the resulting frequency resolution I can obtain?
Like if I have a 2,000 Hz and 1,999 Hz sine wave, how would I determine the length of FFT needed to accurately tell the difference between those two... | The frequency resolution is dependent on the relationship between the FFT length and the sampling rate of the input signal.
If we collect 8192 samples for the FFT then we will have:
$$\frac{8192\ \text{samples}}{2} = 4096\ \,\text{FFT bins}$$
If our sampling rate is 10 kHz, then the Nyquist-Shannon sampling theorem s... |
I wanted to produce a 1 GB random file, so I used following command.
```dd if=/dev/urandom of=output bs=1G count=1
```
But instead every time I launch this command I get a 32 MB file:
```$ dd if=/dev/urandom of=output bs=1G count=1
0+1 records in
0+1 records out
33554431 bytes (34 MB, 32 MiB) copied, 0,288321 s, 116 MB... | ```bs```, the buffer size, means the size of a single read() call done by dd. For example, both ```bs=1M count=1``` and ```bs=1k count=1k``` will result in a 1 MiB file, but the first version will do it in a single step, while the second will do it in 1024 small chunks.
Regular files can be read at nearly any buffer s... |
The treads on my road bike's 28C tires are almost completely gone—they only persist along the shoulders of the tire. Do the treads matter? What is a good indicator of when the tire as a whole needs to be replaced? | The tread on a road bike's tires is really quite unimportant and purely cosmetic. Road bike tires have tread patterns because they sell better, not because they perform better.
Here's some questions to ask to decide about replacing a tire:
* Can you see any of the fabric?
* Are you getting flats more easily than you u... |
Is there a way to create an index on a property/column using fluent configuration, instead of using the new ```IndexAttribute``` ? | Currently there is no "first class support" for creating a index via the fluent API, but what you can do is via the fluent API you can mark properties as having attributes from the Annotation API. This will allow you to add the ```Index``` attribute via a fluent interface.
Here are some examples from the work item fro... |
When I do ```\footnote{}``` for a value in a table, the footnote doesn't show up. How do I get it to show up? Also, is it possible to get it to show up at the bottom of the table rather than the bottom of the page? | This is a classic difficulty in LaTeX.
The problem is how to do layout with floats (figures and tables, an similar objects) and footnotes. In particular, it is hard to pick a place for a float with certainty that making room for the associated footnotes won't cause trouble. So the standard ```tabular``` and ```figure`... |
Why is kVA not the same as kW? | Both watts and volt-amps come from the same equation, $P=IV$, but the difference is how they're measured.
To get volt-amps, you multiply root mean square (RMS) voltage ($V$) with RMS current ($I$) with no regard for the timing/phasing between them. This is what the wiring and pretty much all electrical/electronic compo... |
In this Creation magazine reprint of a 1994 article titled Exploding stars point to a young universe, Young-Earth Creationist, Jonathan Sarfati argues that the scarcity of Supernova remnants (SNRs) in the sky suggests the Milky Way galaxy is less than billions of years old.
On average, a galaxy like our own, the Milk... | There are many reasons why this is wrong. The first one is the assumption of 1 supernova per 25 years. That was the value arrived at in Gustav Tammann's article published in 1970. Others got values up to 100 years (Tammann himself changed his value later). All these values are really only good guesses.
Worse errors ar... |
Why are we building larger land-based telescopes instead of launching larger ones into space? | Because it's cheaper.
(1) With adaptive optics you can get 0.1 arc second resolution on the ground (admittedly only on a mountain top with particularly good air flow, but still!). This eliminates one of the major advantages of space until you get above several meters mirror diameter.
(2) Rocket fairings are the shrouds... |
Why can we see the dust particles in a narrow beam of light (and not in an all lighted area)? | Your inability to see the dust until you narrow the slit has nothing to do with the narrowness of the beam but instead the dynamic range of light that your eye can see at one time.
A bit of searching turns up reports of a contrast ratio for you eye at one time as between 100:1 and 1000:1. This means if you're in a room... |
What is the difference between ```warnings.warn()``` and ```logging.warn()``` in terms of what they do and how they should be used? | Here are the differences:
* ```logging.warning``` just logs something at the ```WARNING``` level, in the same way that ```logging.info``` logs at the ```INFO``` level and ```logging.error``` logs at the ```ERROR``` level. It has no special behaviour.
* ```warnings.warn``` emits a ```Warning```, which may be printed t... |
In Greek mythology, the words "Titan" and "God" seem to be used interchangeably. For example, Zeus is a God, but Cronus (his father) was a Titan. So what is the difference between a Titan and a God in Greek mythology? | A 'god' is synonymous to a 'deity'; the Titans and Titanesses were gods, they were members of the second order of divine beings - after Gaia and Uranus, and the other primordial deities.
Cronus and his fellow Titans comprised the second Ancient Greek pantheon (the first comprising of deities such as Ananke, Gaea, and ... |
I am currently trying to decipher Mazur's Eisenstein ideal paper (not a comment about his clarity, rather about my current abilities). One of the reasons I am doing that is that many people told me that the paper was somehow revolutionary and introduced a new method into number theory.
Could you explain exactly what s... | First, Mazur's paper is arguably the first paper where the new ideas (and language) of the Grothendieck revolution in algebraic geometry were fully embraced and crucially used in pure number theory. Here are several notable examples: Mazur makes crucial use of the theory of finite flat group schemes to understand the ... |
Tracing XML request/responses with JAX-WS | Here is the solution in raw code:
```Endpoint ep = Endpoint.create(new WebserviceImpl());
List handlerChain = ep.getBinding().getHandlerChain();
handlerChain.add(new SOAPLoggingHandler());
ep.getBinding().setHandlerChain(handlerChain);
ep.publish(publishURL);
```
Where SOAPLoggingHandler is (ripped from linked examples... |
In Vim, how do I insert characters at the beginning of each line in a selection?
For instance, I want to comment out a block of code by prepending ```//``` at the beginning of each line assuming my language's comment system doesn't allow block commenting like ```/* */```. How would I do this? | The general pattern for search and replace is:
```:s/search/replace/
```
Replaces the first occurrence of 'search' with 'replace' for current line
```:s/search/replace/g
```
Replaces all occurrences of 'search' with 'replace' for current line, 'g' is short for 'global'
This command will replace each occurrence of 'sear... |
Why doesn't the nuclear fusion in a star make it explode? | The fusion that occurs in the core of the Sun occurs in nothing like the conditions you might be thinking of in a bomb, or a fusion reactor. In particular, it occurs at much lower temperatures and at a much lower rate. A cubic metre of material in the solar core is only releasing around 250 W of power by fusion.
The fu... |
Does hot water freeze faster than cold water? | In certain settings, cold water freezers slower than hot water. This is called the Mpemba effect:
Hot water can in fact freeze faster than cold water for a wide range of experimental conditions. This phenomenon is extremely counterintuitive, and surprising even to most scientists, but it is in fact real. It has been s... |
O que é Reflection. Por que é útil?
* É recomendável usar em projetos?
* Como usar?
* Em quais situações Reflection pode ser usado? | Reflection é um termo usado para indicar a capacidade de obter metadados sobre o próprio programa compilado, em português pode-se referir a isso como reflexão mesmo.
Como assim, metadados?
Obter informações sobre os tipos de dados, de forma dinâmica, é muito importante para códigos que atuam sobre objetos que não se co... |
What is the difference between minimum and infimum? | The minimum is attained, the infimum isn't necessarily.
Example.
Let $f(x) = \frac{1}{x}$. Then $f$ has no minimum value on the interval $(0,\infty)$. The minimum is the smallest element in the set. That is
$$
\min\{f(x)\mid x\in (0,\infty)\}
$$
doesn't exist because there is not smallest number in the set.
Another ex... |
I have extremely bad posture, what can I do? | You can do stretches, strengthening and breathing exercises to improve your posture. But you also have to become aware of your posture and find a way to interrupt prolonged sitting intervals with brief breaks. A good ergonomic chair is also helpful.
## Musculo-Skeletal Effects of Poor Sitting Posture
Poor sitting po... |
How to add margin top to ```class="row"``` elements using twitter bootstrap framework? | Editing or overriding the row in Twitter bootstrap is a bad idea, because this is a core part of the page scaffolding and you will need rows without a top margin.
To solve this, instead create a new class "top-buffer" that adds the standard margin that you need.
```.top-buffer { margin-top:20px; }```
And then use it... |
In FTL: Faster Than Light, what triggers crew experience increases? | ###Piloting
A crew member who is controlling a helm gains one point of experience for each incoming projectile that is dodged during combat. This includes asteroids, so long as you are in combat at the time. (Note that the dodges do not count while you ship is under the effects of +60% evasion from a cloak.)
This can... |
In the python built-in open function, what is the exact difference between the modes ```w```, ```a```, ```w+```, ```a+```, and ```r+```?
In particular, the documentation implies that all of these will allow writing to the file, and says that it opens the files for "appending", "writing", and "updating" specifically, bu... | The opening modes are exactly the same as those for the C standard library function ```fopen()```.
The BSD ```fopen``` manpage defines them as follows:
The argument mode points to a string beginning with one of the following sequences (Additional characters may follow these sequences.):
* ``r'' Open text file for ... |
How can democracy not be the rule of the poor? | Here are some possible explanations why democracy is not necessarily the rule of the poor:
* Voters voting by habit, not by analysis. Many people vote the same way their parents voted. Other vote exactly the opposite way. Neither involves analysis of their objective economic interest.
* A middle class believing to be ... |
How can I write colored text to the Windows console with C++? That is, how can I write different text with different colors? | ANSI escape color codes are: 0=black 1=blue 2=green and so on to 15=white; colorattribute = foreground + background * 16.
To get red text on yellow use 4 + 14*16 = 228, light red on yellow would be 12 + 14*16 = 236.
Here is an example for coloring text in the Windows console:
```
HANDLE hConsole = GetStdHandle(STD_... |
What's the best way to create a temporary file in Android?
Can File.createTempFile be used? The documentation is very vague about it.
In particular, it's not clear when temporary files created with ```File.createTempFile``` are deleted, if ever. | Here is an example:
```
File outputDir = context.getCacheDir(); // context being the Activity pointer
File outputFile = File.createTempFile("prefix", ".extension", outputDir);
```
Explanation:
1. The `getCacheDir()` method returns the directory on the filesystem where your app can create cache files.
2. The `createTem... |
I have javascript function like this:
```function myFunction(number) {
var x=number;
...
... more initializations
//here need to wait until flag==true
while(flag==false)
{}
...
... do something
}
```
The problem is that the javascript is stuck in the while and stuck my program. so my que... | Because javascript in a browser is single threaded (except for webworkers which aren't involved here) and one thread of javascript execution runs to completion before another can run, your statement:
```while(flag==false) {}
```
will simply run forever (or until the browser complains about a non-responsive javascript l... |
According to this famous blog post, the effective transcript length is:
$\tilde{l}_i = l_i - \mu$
where $l_i$ is the length of transcript and $\mu$ is the average fragment length. However, typically fragment length is about 300bp. What if when the transcript $l_i$ is smaller than 300? How do you compute the effective l... | The effective length is $\tilde{l}_i = l_i - \mu + 1$ (note the R code at the bottom of Harold's blog post), which in the case of $\mu
Regarding choosing a particular transcript, ideally one would use a method like salmon or kallisto (or RSEM if you have time to kill). Otherwise, your options are (A) choose the major... |
What is the significance of 1/1/1753 in SQL Server? | The decision to use 1st January 1753 (```1753-01-01```) as the minimum date value for a datetime in SQL Server goes back to its Sybase origins.
The significance of the date itself though can be attributed to this man.
Philip Stanhope, 4th Earl of Chesterfield. Who steered the Calendar (New Style) Act 1750 through the ... |
I saw this video where someone says that electromagnetic wave is a chain reaction of electric and magnetic fields creating each other so the chain of wave moves forward.
I wonder where the photon is in this explanation. What is the relation between electromagnetic wave and photon? | Both the wave theory of light and the particle theory of light are approximations to a deeper theory called Quantum Electrodynamics (QED for short). Light is not a wave nor a particle but instead it is an excitation in a quantum field.
QED is a complicated theory, so while it is possible to do calculations directly in... |
In The Light Fantastic, after talking about the dimensions of the Pyramid of Tsort, it says
All in all, it was a lot of effort to go through just to sharpen a razor.
What's the joke here? | In the real world, there is or was a belief, brought on by the Egyptomania of the early 20th century, that pyramids had special powers—including, specifically, the power to sharpen or maintain the sharpness of razor blades.
Pyramid power refers to the belief that the ancient Egyptian pyramids and objects of similar ... |
In India, we eat rice using our fingers. Generally in the West, a fork or spoon is used. I have tried eating rice with spoon but I don't feel satisfied with it.
We eat dry rice but we mix curry and vegetables with it and then eat it with our hands.
Is there a way to eat rice with your hands in front of Westerners such ... | First and foremost, you can eat the way you want. When it comes to western culture, the only thing that is generally disliked are noises, eating with the mouth wide open (included speaking with full mouth), and (excessively) dirtying the table. Eating rice with hands will be seen (mostly) as strange, not disgusting.
S... |
The typical argument goes like this:
Without net neutrality, cable companies could censor websites, favoring their own business partners.
Typically, proponents of legislation point to some perceived injustice, and argue that new laws are needed to address it. But the very use of the subjunctive in the quotation (c... | There have been a few examples, in part, these examples have pushed this more into the spotlight. It's often under the term 'traffic shaping' if you are interested, here is Sandvine, a company that offers those shaping services. If you are interested in the peer2peer domain (which is heavily bringing this issue to the ... |
Does having a longer Ethernet cable slow your connection? | For all practical purposes, there will be no effect on the speed of your connection.
There will be a very insignificant amount of delay due to long cables. This won't affect the maximum speed of your connection, but it would cause some latency. pjc50 points out that it's about a nanosecond for every foot of cable len... |
Border around formatted text in Inkscape | Here is solution step by step:
* Create some flowed text by using the text tool to first drag a rectangle and then type.
* Separately, create a rectangle roughly around the text (really, the rectangle can be anywhere)
* With the rectangle selected, chose "Path" > "Linked Offset". Then grab the small diamond and drag i... |
I learned about the equilibrium constant. Now, I've seen that the equilibrium constant of burning is extremely small $(K \ll 1)$. here, I have a question. you see, $K$ is still NOT 0, which means that the forward reactions happen at least a tiny bit. Then, shouldn't we see some parts of anything burning at least a litt... | The equilibrium constant for combustion of organic matter in air with oxygen is not small, but extremely large ($K_\mathrm{eq} \gg 1$), as is expected from a reaction that is simultaneously very exothermic and (usually) increases entropy due to the formation of more gaseous molecules than the input oxygen.
The major r... |
The name "Bleach" seems to be having no relevance to the plot unlike most other series. Was it just chosen at Kubo-sensei's whim or does it have some significance? Maybe some cultural significance associated with shinigami, etc. that I am now aware of? | Kubo himself has commented on this. Below is the quote from Bleach Answers Wiki:
> The title wasn't Bleach when Tite Kubo decided to draw a story about Shinigami. This was before he drew the one-shot manga that appeared in Akamaru Jump. The weapon wasn't a sword, but a scythe. Only Rukia had a scythe and the other cha... |
Was the Millennium Falcon a one-off or was it mass produced? | The Millennium Falcon is not unique; it was a model YT-1300f Corellian light freighter. This implies that there are other similar ships, including other variations on the YT-1300 model.
You can find a lot of information about the Millennium Falcon in a companion book, Star Wars: The Force Awakens: Incredible Cross-Sec... |
Usually when I see lists of things to do to be more energy efficient, they require one to own their own home. What can I do to be more energy efficient in an apartment?
For example, I can't install solar panels, I can't upgrade/change my appliances, I can't install better insulation or windows, and I can't install a p... | There are a lot of little things you can do that can add up. Here are some suggestions:
* Wash clothes in cold water only.
* Turn your freezer/refrigerator up a few degrees.
* Purchase insulated curtains/shades, and close them during the day when you are at work.
* Make sure your furniture is arranged so that it is n... |
Is there any way to exit ```less``` without clearing the screen? | This is actually a function of the terminal emulator you are using (xterm, gnome-terminal, konsole, screen). An alternate screen, or altscreen, gets launched when programs such as ```less``` or ```vim``` are invoked. This altscreen has no history buffer and exits immediately when you quit the program, switching back to... |
How can I do 'insert if not exists' in MySQL? | In MySQL, ```ON DUPLICATE KEY UPDATE``` or ```INSERT IGNORE INTO table``` can be viable solutions.
* An example of ```ON DUPLICATE KEY UPDATE``` update based on mysql.com:
```
INSERT INTO table (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=c+1;
UPDATE table SET c=c+1 WHERE a=1;
```
* An example of INSERT IGNOR... |
What does ```class``` do in Ruby? | First, the ```class``` syntax opens up ```foo```'s singleton class (eigenclass). This allows you to specialise the behaviour of methods called on that specific object.
```a = 'foo'
class << a
def inspect
'"bar"'
end
end
a.inspect # => "bar"
a = 'foo' # new object, new singleton class
a.inspect # => "foo"
... |
"I have a problem where i'm initialising a variable on the scope in a controller. Then it gets changed in another controller when a user logs in. This variable is used to control things such as the navigation bar and restricts access to parts of the site depending on the type of user, so its important that it holds its... | You've got basically 2 options for "global" variables:
* use a ```$rootScope```
* use a service
```$rootScope``` is a parent of all scopes so values exposed there will be visible in all templates and controllers. Using the ```$rootScope``` is very easy as you can simply inject it into any controller and change values ... |
How do I initialize a TypeScript Object with a JSON-Object? | This question is quite broad, here are two solutions.
### Solution 1: Helper Method
Here's an example of using a Helper Method that you could change to fit your needs:
```class SerializationHelper {
static toInstance(obj: T, json: string) : T {
var jsonObj = JSON.parse(json);
if (typeof obj["fromJS... |
Why is digital photography so expensive? | Digital photography is not expensive but buying into it is.
With film photography camera and lenses were a moderate investment but these lasted quite long. Even a battery in a film camera would last several years. Cameras and lenses were mechanical and much simpler than today's models. This made them require less expe... |
If user input is inserted without modification into an SQL query, then the application becomes vulnerable to SQL injection, like in the following example:
```$unsafe_variable = $_POST['user_input'];
mysql_query("INSERT INTO `table` (`column`) VALUES ('$unsafe_variable')");
```
That's because the user can input somethin... | The correct way to avoid SQL injection attacks, no matter which database you use, is to separate the data from SQL, so that data stays data and will never be interpreted as commands by the SQL parser. It is possible to create an SQL statement with correctly formatted data parts, but if you don't fully understand the de... |
I want to be able to output the current loop iteration to my template.
According to the docs, there is a ```loop.counter``` variable that I am trying to use:
```
{% for user in userlist %}
*
{{ user }} {{loop.counter}}
{% if loop.counter == 1 %}
This is the First user
{% endif %}
{% en... | The counter variable inside the loop is called loop.index in Jinja2.
```
>>> from jinja2 import Template
>>> s = "{% for element in elements %}{{loop.index}} {% endfor %}"
>>> Template(s).render(elements=["a", "b", "c", "d"])
1 2 3 4
```
In addition to `loop.index`, there is also
* `loop.index0` (index starting at ... |
Are the players on the same team as the DM? | The GM isn't on a team, they’re the referee.
The way Pathfinder, D&D, and similar games work is that there are one or more player characters (the "party") that are controlled by the players.
The GM (DM, in D&D) usually doesn't run a player character (PC), but they are responsible for representing all aspects of the wor... |
How can I adapt Ubuntu to a high resolution display?
I have a display with 3200x1600px on only 11'' and everything looks really tiny. | There are some steps to take:
1. System wide Menu and titlebar scaling
Starting with Ubuntu 14.04 we have an option that helps a bit:
Scaling Support
open the System Settings (here in english:)
```LANG=c unity-control-center
```
Go to "Displays" and set the "Scale for menu and title bars".
Since Ubuntu 17.10 the scali... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.