source stringclasses 5
values | query stringlengths 12 7.84k | response stringlengths 15 17.7k |
|---|---|---|
stackexchange | Suppose I wrote that I will be killed by a UFO falling from space in the year 2315 while I am lifting.
Will the Note increase my lifespan? In other words, will I still be alive by then? | No. There are some rules that prevent this. From the Rules of the Death Note wiki:
1. The 23-days rule
How to use: XXVII
* [...]
* If you write, “die of disease” for the cause of death, but only write a specific time of death without the actual name of disease, the human will die from an adequate disease. Bu... |
stackexchange | I have an Affa Protector enchanted with Unhallowed Pact ... My opponent kills my Affa with Dread Slaver ...
Who will take control of the creature at the end? This is taking into consideration that my aura spell was cast 5 turns ago. Meaning my aura spell is NOT on the stack. | It depends on whose turn it is.
Both abilities trigger at the same time, and so will be put on the stack together. Abilities are put on the stack in APNAP (Active Player, Non-Active Player) order.* This means that the player whose turn it is puts their ability on the stack, then the other player does. That second playe... |
stackexchange | I've found that some people call JavaScript a "dynamically, weakly typed" language, but some even say "untyped"? Which is it really? | strong/weak can be thought of in relation to how the compiler, if applicable, handles typing.
* Weakly typed means the compiler, if applicable, doesn't enforce correct typing. Without implicit compiler interjection, the instruction will error during run-time.
```"12345" * 1 === 12345 // string * number => number
```... |
stackexchange | I was fixing my laptop, and as you may know, laptops have a lot of small screws to take out when you are fixing it. One of the screws fell into the floor (the floor has carpet on it), and I was unable to follow the screw with my sight. If I don't follow the screw with my sight when it falls, there is a high chance that... | This is why you should always have spare screws on hand. Fortunately, there is a way:
## Light Method
Most screws are silver. Shine a flashlight into the carpet and look for little silvery glints. This may take some time, but you'll probably find it. If your carpet is unnaturally thick...
## Magnet Method
Take a powe... |
stackexchange | What is the difference between mutex and critical section? Please explain from Linux, Windows perspectives?
I am programming in C#, would these two terms make a difference. Please post as much as you can, with examples and such....
Thanks | From a theoretical perspective, a critical section is a piece of code that must not be run by multiple threads at once because the code accesses shared resources.
* A mutex is an algorithm (and sometimes the name of a data structure) that is used to protect critical sections.
* Semaphores and Monitors are common imple... |
stackexchange | What is the purpose of the single underscore "_" variable in Python? What is the meaning of ```_``` after ```for``` in this code?
```if tbh.bag:
n = 0
for _ in tbh.bag.atom_set():
n += 1
``` | ```_``` has 3 main conventional uses in Python:
1. To hold the result of the last executed expression in an interactive interpreter session (see docs). This precedent was set by the standard CPython interpreter, and other interpreters have followed suit.
2. For translation lookup in i18n (see the gettext documentatio... |
stackexchange | What is the difference between doing:
```ptr = malloc (MAXELEMS * sizeof(char *));
```
or:
```ptr = calloc (MAXELEMS, sizeof(char*));
```
When is it a good idea to use calloc over malloc or vice versa? | ```calloc()``` gives you a zero-initialized buffer, while ```malloc()``` leaves the memory uninitialized.
For large allocations, most ```calloc``` implementations under mainstream OSes will get known-zeroed pages from the OS (e.g. via POSIX ```mmap(MAP_ANONYMOUS)``` or Windows ```VirtualAlloc```) so it doesn't need to ... |
stackexchange | Why would I want to use Kotlin's coroutines? It seems that the RxKotlin library is much more versatile. Kotlin's coroutines look significantly less powerful and more cumbersome to use in comparison. I base my opinion on coroutines on this design talk by Andrey Breslav (JetBrains) Slideshow from the talk is accessible h... | Kotlin coroutines are different from Rx. It is hard to compare them apples-to-apples, because Kotlin coroutines are a thin language feature (with just a couple of basic concepts and a few basic functions to manipulate them), while Rx is a pretty heavy library with quite large variety of ready-to-use operators. Both are... |
stackexchange | How do I get a ```PriorityQueue``` to sort on what I want it to sort on?
Also, is there a difference between the ```offer``` and ```add``` methods? | ## Java 8 solution
We can use ```lambda expression``` or ```method reference``` introduced in Java 8. In case we have some String values stored in the Priority Queue (having capacity 5) we can provide inline comparator (based on length of String) :
Using lambda expression
```PriorityQueue pq=
new P... |
stackexchange | I've looked in the Apex developer's guide and a saw the Naming Conventions section which has basically only has this:
We recommend following Java standards for naming, that is, classes start with a capital letter, methods start with a lowercase verb, and variable names should be meaningful.
I'm looking for something... | Follow the CamelCase Java conventions, except for VF pages and components start with a lower case letter.
Triggers:
* <ObjectName>Trigger - The trigger itself. One per object.
* <ObjectName>TriggerHandler - Class that handles all functionality of the trigger
* <ObjectName>TriggerTest
Controllers:
* <ClassName>Control... |
stackexchange | When learning some basic French, I was somewhat surprised to learn that phrases of the form "I have found the cat" generally translate almost word-for-word from English (J'ai trouvé le chat). To me, it's not immediately obvious that possession ("I have"/"J'ai") has a correspondence with past tense, although if I think ... | This is what's called a "Sprachbund" feature: it's a trait shared by a bunch of languages in an area, even ones that aren't genetically related. In particular, this one is a feature of the "Standard Average European" Sprachbund, a group of languages centered in Western Europe, and it's one of the features that was orig... |
stackexchange | I'm building a simple helper script for work that will copy a couple of template files in our code base to the current directory. I don't, however, have the absolute path to the directory where the templates are stored. I do have a relative path from the script but when I call the script it treats that as a path relati... | Python have already evolve to the ```__future__``` long time ago. So how about using the amazing ```pathlib``` coming with Python 3.4 to accomplish the task instead of struggling with ```os```, ```os.path```, ```glob ```, ```shutil```, etc.
So we have 3 paths here (possibly duplicated):
* ```mod_path```: which is the ... |
stackexchange | How to send HTML-formatted email in C#? | Setting isBodyHtml to true allows you to use HTML tags in the message body:
```
msg = new MailMessage("xxxx@gmail.com",
"yyyy@gmail.com", "Message from PSSP System",
"This email sent by the PSSP system<br />" +
"<b>this is bold text!</b>");
msg.IsBodyHtml = true;
``` |
stackexchange | I want to sum a list of Integers. It works as follows, but the syntax does not feel right. Could the code be optimized?
```Map integers;
integers.values().stream().mapToInt(i -> i).sum();
``` | This will work, but the `i -> i` is doing some automatic unboxing which is why it "feels" strange. `mapToInt` converts the stream to an `IntStream` "of primitive int-valued elements". Either of the following will work and better explain what the compiler is doing under the hood with your original syntax:
```
integers.v... |
stackexchange | I am beginner of LaTeX. From many examples I found, I notice that it's very common to use command ```\leavevmode```. I can't find any information about this command. Could anyone tell me what's the function of it and how to use it? | The ```\leavevmode``` is defined by LaTeX and plainTeX and ensures that the vertical mode is ended and horizontal mode is entered. In vertical mode, TeX stacks horizontal boxes vertically, whereas in horizontal mode, they are taken as part of the text line.
For example ```\mbox{..}``` is defined as ```\leavevmode\hbox{... |
stackexchange | In Python specifically, how do variables get shared between threads?
Although I have used ```threading.Thread``` before I never really understood or saw examples of how variables got shared. Are they shared between the main thread and the children or only among the children? When would I need to use thread local stora... | In Python, everything is shared, except for function-local variables (because each function call gets its own set of locals, and threads are always separate function calls.) And even then, only the variables themselves (the names that refer to objects) are local to the function; objects themselves are always global, an... |
stackexchange | I grew up in a country where we were not allowed to leave/travel to an other country even when we were able to do so – we had the resources and dual nationality.
After two decades I still can't figure out why dictators, like Kim Jong-un for example, ban people from leaving their home countries?
Could it be that a dicta... | People are resources, dictators (and oppressive regimes in general) don't want them to defect to other countries because they want them working for their regime. Some of them are going to be people that the regime has put their resources into, like scientists and doctors, but even laborers are valuable for actually gat... |
stackexchange | Why can't we kill ourselves by holding our breath? | ## Short answer
Healthy people cannot hold their breaths until unconsciousness sets in, let alone commit suicide.
## Background
According to Parkes (2005), a normal person cannot even hold their breath to unconsciousness, let alone death. Parkes says:
Breath‐holding is a voluntary act, but normal subjects appear un... |
stackexchange | Sometimes while driving in the traffic, I come across a car or two which would be dripping water-like drops from its exhaust steadily in 4-5 second intervals. I tried to ask a couple of people at the local workshops; they say, and I quote, "The car is giving an amazing mileage".
And I am like, what does that ... | It signifies that the car is running absolutely correct. Here is the reason why:
A gasoline (petrol) molecule is made up as such:
C8H18 (or 8 Carbon atoms and 18 Hydrogen atoms)
Energy is obtained from the combustion of it by the conversion of a hydrocarbon to carbon dioxide and water. The combustion of octane follo... |
stackexchange | Why can't MX records point to an IP address? | The whole idea behind the mail exchange (MX) record is to specify a host or hosts which can accept mail for a domain. As specified in RFC 1035, the MX record contains a domain name. It must therefore point to a host which itself can be resolved in the DNS. An IP address could not be used as it would be interpreted as a... |
stackexchange | Why is ```SELECT *``` bad practice? Wouldn't it mean less code to change if you added a new column you wanted?
I understand that ```SELECT COUNT(*)``` is a performance problem on some DBs, but what if you really wanted every column? | The asterisk character, "*", in the SELECT statement is shorthand for all the columns in the table(s) involved in the query.
Performance
The ```*``` shorthand can be slower because:
* Not all the fields are indexed, forcing a full table scan - less efficient
* What you save to send ```SELECT *``` over the wire risks ... |
stackexchange | I did my training around the Seattle area, and was told that landing at SeaTac Airport (the region's major International/Commercial airport), while not strictly forbidden, was definitely frowned upon because it can slow down and interfere with the big planes on schedules. To discourage GA aircraft from using the big ai... | Can you? Absolutely, and air traffic control will treat you (almost) like any other airplane. You are supposedly handled on a first-come-first-serve basis (reality is slightly different with different aircraft speeds, etc.). Do the airlines like it if you slow them down? No, but it's part of the system and the way tha... |
stackexchange | I need a way to compare multiple strings to a test string and return the string that closely resembles it:
```TEST STRING: THE BROWN FOX JUMPED OVER THE RED COW
CHOICE A : THE RED COW JUMPED OVER THE GREEN CHICKEN
CHOICE B : THE RED COW JUMPED OVER THE RED COW
CHOICE C : THE RED FOX JUMPED OVER THE BROWN COW
```
... | Fuzzy String Matching is the process of performing a human-like estimation of the similarity of two words or phrases. In many cases, it involves implementing the Levenshtein distance algorithm, which determines how many changes must be made to a string or phrase to turn it into another string or phrase. The following i... |
stackexchange | Given the following code:
```var arr = [1,2,3,4,5];
var results: number[] = await arr.map(async (item): Promise => {
await callAsynchronousOperation(item);
return item + 1;
});
```
which produces the following error:
TS2322: Type 'Promise[]' is not assignable to type 'number[]'.
Type 'Promise i... | The problem here is that you are trying to ```await``` an array of promises rather than a Promise. This doesn't do what you expect.
When the object passed to ```await``` is not a Promise, ```await``` simply returns the value as-is immediately instead of trying to resolve it. So since you passed ```await``` an array (of... |
stackexchange | Why don't helicopters use reaction wheels to counter the main rotor? | You're talking about a device (in helicopters the tail fan imparting horizontal thrust) that counteracts the torque imparted on the main rotor (and therefore on the helicopter) by the surrounding air as the main rotor is dragged through the air.
You propose instead to impart an opposite torque through a reaction wheel... |
stackexchange | When configuring cron to run a command every other day using the "Day of Month" field, like so:
```1 22 */2 * * COMMAND
```
it runs every time the day of month is odd: 1,3,5,7,9 and so on.
How can I configure cron to run on days of month that are even like 2,6,8,10 and so on (without specifying it literally, which is ... | The syntax you tried is actually ambiguous. Depending on how many days are in the month, some months it will run on odd days and some on even. This is because the way it is calculated takes the total number of possibilities and divides them up. You can override this strage-ish behavior by manually specifying the day ra... |
stackexchange | Is there a way to have a private setter for a property in TypeScript?
```class Test
{
private _prop: string;
public get prop() : string
{
return this._prop;
}
private set prop(val: string)
{
//can put breakpoints here
this._prop = val;
}
}
```
Compiler complains that ... | The TypeScript specification (8.4.3) says"
Accessors for the same member name must specify the same accessibility
So you have to choose a suitable alternative. Here are two options for you:
You can just not have a setter, which means only the ```Test``` class is able to set the property. You can place a breakpoint ... |
stackexchange | When learning vocabulary, especially with the use of SRS (Spaced Repetition System), it is interesting to use flashcards. A commonly encountered problem is how to formulate those for maximum efficiency.
How does learning vocabulary through sentences, thus giving context to the used words, compare to learning to recogni... | It's usually best to avoid dichotomies like "Is strategy X better or strategy Y better?". In most cases, strategies are not mutually exclusive but complementary.
With vocabulary learning, using just one strategy is probably the least efficient. This is because every strategy has certain strengths (certain skills it b... |
stackexchange | Can I spend the night alone in a tent in a forest outside Stockholm in -20°C without risking my life?
The backstory
From the end of January, I'm starting my studies in a suburb of Stockholm. I've decided to, if it turns out plausible, not rent an apartment, but live in a tent. (This is not out of frugality, but out of... | Yes, it is definitely doable. -20°C is only -4°F. The real question is whether it is doable by you at the level of discomfort and hassle you are willing to put up with. Only you can answer that. At best we can point out what the hassles and discomforts will be.
First, your fear of dying of cold in your sleep i... |
stackexchange | Why is the volt not identical to the full name Volta, unlike the other electrical units ohm, ampere, coulomb, tesla, weber and henry? Is there a historical explanation, was the volt introduced at a different time? | The volt, ohm and farad were introduced by the same person, Latimer Clark, a cable engineer, in a paper in 1861. He started the tradition of naming units after scientists. He initially distorted all names: the unit names ohma, volt, galvat (from Galvani), and farad (from Faraday). In his words, he "neglected etymologic... |
stackexchange | We can define cross products mathematically like if we take two vectors, we can find another vector with certain properties but why do we use it in physics, if we consider a hypothetical physical quantity like force which is equal to cross product of certain vectors?
For example, the force exerted on a charge in mot... | This is a great question. The dot and cross products seem very mysterious when they are first introduced to a new student. For example, why does the scalar (dot) product have a cosine in it and the vector (cross) product have a sine, rather than vice versa? And why do these same two very non-obvious ways of "multiplyin... |
stackexchange | I have a web project in my solution file that is "unavailable" when I open the solution. When I right-click on the web project and reload the project, I get the following error:
```
The Web Application Project mycompany.myapp.mywebproject is configured to use IIS. The Web Server 'http://localhost/MyWebApp could not be ... | When this happens the easiest solution is to make the virtual directory manually.
First of all, you need to make sure you have the right version of ASP.Net installed and that you have installed the IIS extensions.
To do this, go to the relevant .net version's folder in C:\(Windows)\Microsoft.NET\Framework\(dotnetver)\... |
stackexchange | Why is it hard to draw people running in animes? | The walk cycle is considered to be one of the most basic aspects of animation. American animators and animation enthusiasts often times scorn the Japanese styles and methods of animation as lazy, while Japanese anime enthusiasts deride the American style as clunky or too comical.
Why is that you ask? The answer lies i... |
stackexchange | Malachi 4:5:
I will send you the prophet Elijah. He will come before the day of the Lord arrives. It will be a great and terrifying day
Jesus says in Matthew 11:14
"and if you are willing to believe their message, John is Elijah, whose coming was predicted"
Jesus says in Mathew 17:12
But I tell you, Elijah ... | Faulty Premise #1: John the Baptist was a reincarnation of Elijah
When Jesus asked Peter who people said he was, he answered that some people thought that Jesus was Elijah come back. Peter knew better and said Jesus was the Christ. In any event, John the Baptist himself directly denied the claim (see John 1:19-21).
W... |
stackexchange | I see hugely varied performance depending on how many newlines there are in the file I'm visiting.
Here's an example. I have two JSON files:
```$ wget https://github.com/Wilfred/ReVo-utilities/blob/a4bdc40dd2656c496defc461fc19c403c8306d9f/revo-export/dictionary.json?raw=true -O one_line.json
$ python -m json.tool prett... | Emacs' handling of long lines is not very well optimized. For a number of operations, Emacs has to scan the whole line repeatedly. For example, to display a line, Emacs has to figure out the height of the line, which requires scanning the whole line to find the tallest glyph. Additionally, scanning for bidirectional di... |
stackexchange | Sooner or later we come across a task in our project, with which we are totally unfamiliar ('we' as in PM, but also possibly the staff assigned to do this particular task).
How can we estimate amount of time/work/resources needed to complete such a task? What margins of error should we assume? | Don't place too much confidence on your first guess just because you've used a sophisticated formula to derive your estimate. Do your best, move on, plan to revise your estimate, don't let bad estimates linger and destroy the discipline of your project schedule ... errors in time estimates are likely to be lognormally... |
stackexchange | Why is Nazi-Germany commonly referred to as "The Third Reich" in English? Why is reich not translated when Dritten ("third") is?
And what is the English synonym of reich? Realm?
Austria (Republik Österreich), Norway (Kongeriket Norge) and Sweden (Konungariket Sverige) all have reich (or the Norwegian/Swedish correspond... | Although English historians have defined Reich as being a strictly German concept of sovereign rule, in the German language itself it means "Empire". In English, we speak of the Holy Roman Empire; in German, it is the HRR or "Heiliges Römisches Reich Deutscher Nation".
Wiktionary quotes Busching, who in 1762 explaine... |
stackexchange | If we fold a paper and then apply pressure on the newly formed crease, it seems that the paper's surface gets a permanent deformation but what exactly has happened to the paper at a molecular scale? | Basically, a fold or crease in paper will remain because the structure of the fibers in the paper have become irreversibly damaged. This happens because the paper is bent/compressed beyond its elastic limit.
Chemically, paper is mainly composed of cellulose from plant fibers. Cellulose is an organic polymer, which ha... |
stackexchange | In general, there are two types of syntax of defining functions - Something like C, C++, C#, or Java (```int functionName(char arg)```) vs the ML (and others) tradition of defining the return type after the function (and using something like a ```fun``` keyword to define a function - like ```fun functionName(char arg):... | Dennis Ritchie’s paper on The Development of the C Language gives some idea of the reasoning behind this: namely, the fundamental rule in C that declaration syntax should match expression syntax"
For each object of such a composed type, there was already a way to mention the underlying object: index the array, call th... |
stackexchange | I am new to TeX, working on it for about 2 months. Have not yet figured out how to script the 'curvy L' for Lagrangian and/or for Laplace Transforms.
As of now I am using the 'L' - which is not good! :-(
Any help?
UPDATE The 2 best solutions are;
```\usepackage{ amssymb }
\mathcal{L}
```
and
```\usepackage{ mathrsfs }... | You have been told how to get a curved L. But here's some more general advice, which also applies in this situation: In cases such as this, always create your own shortcut macro, say
```\newcommand{\Lagr}{\mathcal{L}}
```
This way, if you ever decide that that curly L is not quite the one you like, it is easy to switc... |
stackexchange | My son doesn't want to share anything with other kids, and if some kid even so much as touches his toy, he pushes the kid. He shouts and cries at the same time, and tries to express his anger by pushing and hitting the kid. I feel so embarrassed in front of other parents.
And when he is at home with me and doing somet... | Welcome to the "Terrible Two's"!
Your son behaves typically for his age. At 2 he starts to assert himself and express his demands. It's likely that he has also learned that he gets his way when he throws a tantrum. For a 2-year old screaming, hitting or even biting is a normal way to express his anger - at least he w... |
stackexchange | What are the differences between the Strategy design pattern and the State design pattern? please explain the difference in layman's terms? | The difference simply lies in that they solve different problems:
* The State pattern deals with what (state or type) an object is (in) -- it encapsulates state-dependent behavior, whereas
* the Strategy pattern deals with how an object performs a certain task -- it encapsulates an algorithm.
The constructs for... |
stackexchange | Why don't Tour de France riders always ride their TT bikes? | There are 2 good reasons for this.
First, a TT bike is the most efficient machine for flat, fast course racing, where there are a minimum of hills. It is not the most efficient machine when it comes to climbing. The body position is far too aggressive for even professional athletes to use in a non-TT style event. A b... |
stackexchange | I remember when the Muslim holy book was the Koran when I was in middle school, but now it's the Quran. But it's always been Qatar and Iraq (but still Kuwait.)
Who decided that 'Q' was going to be represent that sound instead of 'K', and why? | In Arabic, in fact, they've always been separate sounds! The sound we write "K" is spelled with the letter ك in Arabic, and is pronounced a little bit further forward in the mouth; the sound we write "Q" is spelled with the letter ق and pronounced a little bit farther back. In phonetic terms, "K" is a velar sound, and ... |
stackexchange | How do you add Boost libraries in CMakeLists.txt? | Put this in your `CMakeLists.txt` file (change any options from OFF to ON if you want):
```
set(Boost_USE_STATIC_LIBS OFF)
set(Boost_USE_MULTITHREADED ON)
set(Boost_USE_STATIC_RUNTIME OFF)
find_package(Boost VERSION COMPONENTS *boost libraries here*)
if(Boost_FOUND)
include_directories(${Boost_INCLUDE_DIRS})... |
stackexchange | Quando devo fazer essa gravação direto no banco?
Quais as situações?
Eu sei que posso gravar no banco o caminho da imagem. | Além do custo ser mais alto como mencionado, deve-se levar em conta vários fatores:
* Volume de dados: para um baixo volume de dados pode não haver problema. Por outro lado, para armazenamento de grande massa de dados o banco de dados é praticamente inviável. Pergunte ao Facebook ou ao Google se eles usariam banco. O ... |
stackexchange | I need a regular expression that validates a number, but doesn't require a digit after the decimal. ie. ```123 123. 123.4 ``` would all be valid ```123.. ``` would be invalid | Here is the regular expression you can use:
```
/^\d*\.?\d*$/
```
* `^` - Beginning of the line;
* `\d*` - 0 or more digits;
* `\.?` - An optional dot (escaped, because in regex, . is a special character);
* `\d*` - 0 or more digits (the decimal part);
* `$` - End of the line.
This allows for .5 decimal rather than ... |
stackexchange | 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... |
stackexchange | 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... |
stackexchange | 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... |
stackexchange | 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... |
stackexchange | 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... |
stackexchange | 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... |
stackexchange | 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... |
stackexchange | 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 ... |
stackexchange | 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 ... |
stackexchange | 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(... |
stackexchange | Why are the lights inside commercial airplanes turned off during take off and landing? | This is for safety reasons.
Take-off and landing are the two most critical phases of flight and thus, every additional step to ensure survivability, be it even just adjusting the light, is taken.
The interior lights or cabin lights are adjusted to match the exterior environment, so that in case of an emergency, espe... |
stackexchange | The default behaviour of ```LIKE``` and the other comparison operators, ```=``` etc is case-sensitive.
Is it possible make them case-insensitive? | There are 3 main ways to perform a case-insensitive search in Oracle without using full-text indexes.
Ultimately what method you choose is dependent on your individual circumstances; the main thing to remember is that to improve performance you must index correctly for case-insensitive searching.
1. Case your column ... |
stackexchange | 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... |
stackexchange | 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... |
stackexchange | 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... |
stackexchange | 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... |
stackexchange | 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... |
stackexchange | 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... |
stackexchange | What are the major branches of philosophy? | The traditional branches of philosophy generally include
* Aesthetics
* Epistemology
* Ethics
* Logic
* Metaphysics / Ontology
We can go ahead and add a few contemporary branches on to this (more examples could certainly be adduced):
* Philosophy of Science [referring to the hard sciences] (Mathematics, Technology, e... |
stackexchange | 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 ... |
stackexchange | 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... |
stackexchange | 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... |
stackexchange | 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... |
stackexchange | 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... |
stackexchange | 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 ... |
stackexchange | 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 ... |
stackexchange | 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 ... |
stackexchange | I'm working on a project solo and have to maintain my own code. Usually code review is done not by the code author, so the reviewer can look at the code with the fresh eyes — however, I don't have such luxury. What practices can I employ to more effectively review my own code? | First of all, make use of tools to check as much as you can. Tests (backed up with some reasonable code coverage) will give you some confidence of the correctness of the code. Static analysis tools can catch a lot of best practice things. There will always be issues that you need human eyes on to determine though and y... |
stackexchange | 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... |
stackexchange | Best way to start investing, for a young person just starting their career? | First off, I highly recommend the book Get a Financial Life. The basics of personal finance and money management are pretty straightforward, and this book does a great job with it. It is very light reading, and it really geared for the young person starting their career.
Now, with that out of the way, there's really ... |
stackexchange | Quantum state teleportation is the quantum information protocol where a qubit is transferred between two parties using an initial shared entangled state, Bell measurement, classical communication and local rotation. Apparently, there is also something called quantum gate teleportation.
What is quantum gate teleportatio... | Quantum gate teleportation is the act of being able to apply a quantum gate on the unknown state while it is being teleported. This is one of the ways in which measurement-based computation can be described using graph states.
Usually, teleportation works by having an unknown quantum state $|\psi\rangle$ held by Alice... |
stackexchange | 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 ... |
stackexchange | 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... |
stackexchange | Why did people start using CO2 (instead of e.g. oxygen) for carbonated drinks? | CO2 tastes good! Carbonated water is actually a weak carbonic acid solution; this is what you taste. It's like "salt and pepper", but for water.
Slightly acidic water is usually popular, hence lemon juice is sometimes used to taint a jug of water in times when no carbonated water is available.
Carbonated water releas... |
stackexchange | 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... |
stackexchange | 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... |
stackexchange | 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... |
stackexchange | 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 ... |
stackexchange | $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... |
stackexchange | 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) {
... |
stackexchange | 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```. |
stackexchange | "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... |
stackexchange | 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... |
stackexchange | When encoding a logic into a proof assistant such as Coq or Isabelle, a choice needs to be made between using a shallow and a deep embedding. In a shallow embedding logical formulas are written directly in the logic of the theorem prover, whereas in a deep embedding logical formulas are represented as a datatype.
* W... | > What are the advantages and limitations of the various approaches?
* Pros of deep embeddings : You can prove and define things by induction on formulas' structure. Examples of interests are the size of a formula.
* Cons of deep embeddings: You have do deal explicitly with binding of variables. That's usually very l... |
stackexchange | 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... |
stackexchange | 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 ... |
stackexchange | 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... |
stackexchange | 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 =... |
stackexchange | 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... |
stackexchange | I'm running a relatively small one-man business in the software sector. I just started and am trying to create a larger portfolio. For that, I offer some friends free services.
I found a few reasons to send these clients €0,- invoices, mostly similar to the reasons to send 100% discount invoices to charity funds that ... | It depends on the tax system that applies to you, but there can be consequences, and they can be very severe.
Generally economic activity is defined as oriented on profit, so giving anything for free could qualify as self-promotion or donation.
In Poland, for example, only some costs of the company spend on promotion... |
stackexchange | 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... |
stackexchange | 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'... |
stackexchange | 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.