conversations
list
id
stringlengths
7
18
[ { "from": "human", "value": "Suppose I wrote that I will be killed by a UFO falling from space in the year 2315 while I am lifting.\nWill the Note increase my lifespan? In other words, will I still be alive by then? " }, { "from": "gpt", "value": "No. There are some rules that prevent this. From the Rules of the Death Note wiki:\n\n1. The 23-days rule\n\n How to use: XXVII\n \n * [...]\n * 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. But the Death Note can only operate within 23 days (in the human calendar). This is called the 23-day rule.\n \n\n2. Situation/cause of death is impossible \n\n How to Use: LIV\n \n * [...] \n * In the occasion where the cause of death is possible but the situation is not, only the cause of death will take effect for that victim. If both the cause and the situation are impossible, that victim will die of heart attack.\n\nWhile an UFO falling on your head is technically unlikely, but not impossible, the fact that you'll be naturally alive by 2315 is impossible. You'll just shorten your life, not make it longer.\n\n3. Setting death after original lifespan\n\n How to Use: LVII\n \n * In the Death Note, you cannot set the death date longer than the victim’s original life span. Even if the victim’s death is set in the Death Note beyond his/her original life span, the victim will die before the set time.\n" } ]
200-stackexchange
[ { "from": "human", "value": "I have an Affa Protector enchanted with Unhallowed Pact ... My opponent kills my Affa with Dread Slaver ...\nWho 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." }, { "from": "gpt", "value": "It depends on whose turn it is.\nBoth 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 player's ability will resolve first, returning the creature to the battlefield. When the other ability tries to resolve, it fails to find the creature in the graveyard and thus can't return it.\nThus whoever's the active player won't end up with the creature. For multiplayer games where there are multiple NAPs they are put on the stack in turn order starting from the AP, so the last player in turn order with such an effect would take precedence.\n\n* From the rules on Triggered Abilities:\n\n > 603.3b If multiple abilities have triggered since the last time a player received priority, each player, in APNAP order, puts triggered abilities he or she controls on the stack in any order he or she chooses. [...]\n\nThis works with any number of players, starting with the active player and passing around in turn order. In this case, the player furthest away from taking their turn (the last player to put their ability on the stack) would get the creature." } ]
201-stackexchange
[ { "from": "human", "value": "I've found that some people call JavaScript a \"dynamically, weakly typed\" language, but some even say \"untyped\"? Which is it really?" }, { "from": "gpt", "value": "strong/weak can be thought of in relation to how the compiler, if applicable, handles typing.\n\n* Weakly typed means the compiler, if applicable, doesn't enforce correct typing. Without implicit compiler interjection, the instruction will error during run-time.\n```\"12345\" * 1 === 12345 // string * number => number\n```\nStrongly typed means there is a compiler, and it wants you an explicit cast from string to integer.\n```(int) \"12345\" * 1 === 12345\n```\nIn either case, some compiler's features can implicitly alter the instruction during compile-time to do conversions for you, if it can determine that is the right thing to do.\nThus far, JavaScript can be categorized as Not-Strongly-Typed. That either means it's weakly-typed or un-typed.\n\ndynamic/static can be thought of in relation to how the language instructions manipulate types.\n\n* Dynamically typed means the value's type is enforced, but the variable simply represents any value of any type.\n```x = 12345; // number\nx = \"string\"; // string\nx = { key: \"value\" }; // object\ny = 123 + x; // error or implicit conversion must take place.\n```\nStatically typed means the variable type is strongly enforced, and the value type is less-so enforced.\n```int x = 12345; // binds x to the type int\nx = \"string\"; // too late, x is an integer - error\nstring y = 123; // error or implicit conversion must take place.\n```\nThus far, JavaScript can be categorized as Not-Statically-Typed. Also, it appears to be Dynamically Typed, if typed at all. So we need to see what Typing means.\n\nTyped means that the language distinguishes between different types such as string, number, boolean, object, array, null, undefined and so on. Also each operation is bound to specific types. So you cannot divide an integer by a string.\n``` 2 / \"blah\" // produces NaN\n```\nUntyped means the operation of dividing integer by string would result in treating the first four bytes of string as integer. This is because Untyped operations take place directly on bits, there are no types to observe. The outcome will be something quite unexpected:\n``` 2 / \"blah\" // will be treated as 2 / 1500275048\n```\nSince JavaScript behaves according to the definition of being Typed, it must be. And therefore it must be Dynamically Typed, and Weakly Typed.\nIf anybody claims JavaScript is Untyped, it is merely for academic theory, not for practical application." } ]
202-stackexchange
[ { "from": "human", "value": "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 I will not see that screw again.\nMy question is: what kind of method, tool or hack can I use to find small screws that falls into the floor?\nI have tried using the tool with a magnet on the tip, that mechanics use to grab wrenches that falls in inaccessible areas, but had no luck finding the screw." }, { "from": "gpt", "value": "This is why you should always have spare screws on hand. Fortunately, there is a way:\n\n## Light Method\nMost 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...\n\n## Magnet Method\nTake a powerful magnet (like a bar magnet, hardware stores - fridge magnets might work) and run it over the surface where you think the screw is. You should find it. If that still fails...\n\n## Vacuum Method\nTake a good vacuum cleaner. Put a sock over the extending arm, and run it over where you think the screw is. The sock will prevent the screw from being vacuumed up, but it will be stuck to the sock. There will still be enough suction to pick up the screw, even with the sock. If not, get a new vacuum! If that fails...\n\n## Organize your screws\nThere are many useful tools to organize screws. Go to your local RadioShack and get one, or make one out of a magnet for that awesome lifehack feel.\n\n## Stop using carpet!\n[Not a "find your screws" method - a tip about not frying your computer]\nCarpet can cause static discharge, which is very very very bad for a computer (personal experience). Work on a hard floor with an antistatic strap to reduce the chance of frying your PC." } ]
203-stackexchange
[ { "from": "human", "value": "What is the difference between mutex and critical section? Please explain from Linux, Windows perspectives? \nI am programming in C#, would these two terms make a difference. Please post as much as you can, with examples and such....\nThanks" }, { "from": "gpt", "value": "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.\n\n* A mutex is an algorithm (and sometimes the name of a data structure) that is used to protect critical sections.\n* Semaphores and Monitors are common implementations of a mutex.\n\nIn practice there are many mutex implementation availiable in windows. They mainly differ as consequence of their implementation by their level of locking, their scopes, their costs, and their performance under different levels of contention. \n\nAvailiable synchronization primitives.\n\n* Monitor\n* Mutex\n* Semaphore\n* ReaderWriterLock\n* ReaderWriterLockSlim\n* Interlocked\n\nThe ```lock(object)``` statement is implemented using a ```Monitor``` - see MSDN for reference.\n\nIn the last years much research is done on non-blocking synchronization. The goal is to implement algorithms in a lock-free or wait-free way. In such algorithms a process helps other processes to finish their work so that the process can finally finish its work. In consequence a process can finish its work even when other processes, that tried to perform some work, hang. Usinig locks, they would not release their locks and prevent other processes from continuing." } ]
204-stackexchange
[ { "from": "human", "value": "What is the purpose of the single underscore \"_\" variable in Python? What is the meaning of ```_``` after ```for``` in this code?\n```if tbh.bag:\n n = 0\n for _ in tbh.bag.atom_set():\n n += 1\n```" }, { "from": "gpt", "value": "```_``` has 3 main conventional uses in Python:\n\n1. 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.\n\n2. For translation lookup in i18n (see the gettext documentation for example), as in code like\n```raise forms.ValidationError(_("Please enter a correct username"))\n```\n\n3. As a general purpose "throwaway" variable name:\n\n* To indicate that part of a function result is being deliberately ignored (Conceptually, it is being discarded.), as in code like:\n```label, has_label, _ = text.partition(':')\n```\n\n* As part of a function definition (using either ```def``` or ```lambda```), where the signature is fixed (e.g. by a callback or parent class API), but this particular function implementation doesn't need all of the parameters, as in code like:\n```def callback(_):\n return True\n```\n\nThis use case can conflict with the translation lookup use case, so it is necessary to avoid using ```_``` as a throwaway variable in any code block that also uses it for i18n translation (many folks prefer a double-underscore, ```__```, as their throwaway variable for exactly this reason).\n\nLinters often recognize this use case. For example ```year, month, day = date()``` will raise a lint warning if ```day``` is not used later in the code. The fix, if ```day``` is truly not needed, is to write ```year, month, _ = date()```. Same with lambda functions, ```lambda arg: 1.0``` creates a function requiring one argument but not using it, which will be caught by lint. The fix is to write ```lambda _: 1.0```. An unused variable is often hiding a bug/typo (e.g. set ```day``` but use ```dya``` in the next line).\n\nThe pattern matching feature added in Python 3.10 elevated this usage from "convention" to "language syntax" where ```match``` statements are concerned: in match cases, ```_``` is a wildcard pattern, and the runtime doesn't even bind a value to the symbol in that case.\n\nFor other use cases, remember that ```_``` is still a valid variable name, and hence will still keep objects alive. In cases where this is undesirable (e.g. to release memory or external resources) an explicit ```del name``` call will both satisfy linters that the name is being used, and promptly clear the reference to the object." } ]
205-stackexchange
[ { "from": "human", "value": "What is the difference between doing:\n```ptr = malloc (MAXELEMS * sizeof(char *));\n```\nor:\n```ptr = calloc (MAXELEMS, sizeof(char*));\n```\nWhen is it a good idea to use calloc over malloc or vice versa?" }, { "from": "gpt", "value": "```calloc()``` gives you a zero-initialized buffer, while ```malloc()``` leaves the memory uninitialized.\nFor 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 write them in user-space. This is how normal ```malloc``` gets more pages from the OS as well; ```calloc``` just takes advantage of the OS's guarantee.\nThis means ```calloc``` memory can still be "clean" and lazily-allocated, and copy-on-write mapped to a system-wide shared physical page of zeros. (Assuming a system with virtual memory.) The effects are visible with performance experiments on Linux, for example.\nSome compilers even can optimize malloc + memset(0) into calloc for you, but it's best to just use calloc in the source if you want zeroed memory. (Or if you were trying to pre-fault it to avoid page faults later, that optimization will defeat your attempt.)\nIf you aren't going to ever read memory before writing it, use ```malloc``` so it can (potentially) give you dirty memory from its internal free list instead of getting new pages from the OS. (Or instead of zeroing a block of memory on the free list for a small allocation).\n\nEmbedded implementations of ```calloc``` may leave it up to ```calloc``` itself to zero memory if there's no OS, or it's not a fancy multi-user OS that zeros pages to stop information leaks between processes.\nOn embedded Linux, malloc could ```mmap(MAP_UNINITIALIZED|MAP_ANONYMOUS)```, which is only enabled for some embedded kernels because it's insecure on a multi-user system." } ]
206-stackexchange
[ { "from": "human", "value": "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 here." }, { "from": "gpt", "value": "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 designed to address a problem of asynchronous programming, however their approach to solution is very different:\n\n* Rx comes with a particular functional style of programming that can be implemented in virtually any programming language without support from the language itself. It works well when the problem at hand easily decomposes into a sequence of standard operators and not so well otherwise.\n* Kotlin coroutines provide a language feature that let library writers implement various asynchronous programming styles, including, but not limited to functional reactive style (Rx). With Kotlin coroutines you can also write your asynchronous code in imperative style, in promise/futures-based style, in actor-style, etc. \n\nIt is more appropriate to compare Rx with some specific libraries that are implemented based on Kotlin coroutines. \nTake kotlinx.coroutines library as one example. This library provides a set of primitives like ```async/await``` and channels that are typically baked into other programming languages. It also has support for light-weight future-less actors. You can read more in the Guide to kotlinx.coroutines by example.\nChannels provided by ```kotlinx.coroutines``` can replace or augment Rx in certain use-cases. There is a separate Guide to reactive streams with coroutines that goes deeper into similarities and differences with Rx. " } ]
207-stackexchange
[ { "from": "human", "value": "How do I get a ```PriorityQueue``` to sort on what I want it to sort on?\nAlso, is there a difference between the ```offer``` and ```add``` methods?" }, { "from": "gpt", "value": "## Java 8 solution\nWe 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) : \nUsing lambda expression\n```PriorityQueue pq=\n new PriorityQueue(5,(a,b) -> a.length() - b.length());\n```\nUsing Method reference\n```PriorityQueue pq=\n new PriorityQueue(5, Comparator.comparing(String::length));\n```\nThen we can use any of them as:\n```public static void main(String[] args) {\n PriorityQueue pq=\n new PriorityQueue(5, (a,b) -> a.length() - b.length());\n // or pq = new PriorityQueue(5, Comparator.comparing(String::length));\n pq.add(\"Apple\");\n pq.add(\"PineApple\");\n pq.add(\"Custard Apple\");\n while (pq.size() != 0)\n {\n System.out.println(pq.remove());\n }\n }\n```\nThis will print:\n```Apple\nPineApple\nCustard Apple\n```\nTo reverse the order (to change it to max-priority queue) simply change the order in inline comparator or use ```reversed``` as:\n```PriorityQueue pq = new PriorityQueue(5,\n Comparator.comparing(String::length).reversed());\n```\nWe can also use ```Collections.reverseOrder```:\n```PriorityQueue pqInt = new PriorityQueue(10, Collections.reverseOrder());\nPriorityQueue pq = new PriorityQueue(5,\n Collections.reverseOrder(Comparator.comparing(String::length))\n```\nSo we can see that ```Collections.reverseOrder``` is overloaded to take comparator which can be useful for custom objects. The ```reversed``` actually uses ```Collections.reverseOrder```:\n```default Comparator reversed() {\n return Collections.reverseOrder(this);\n}\n```\noffer() vs add()\nAs per the doc \n\n > The offer method inserts an element if possible, otherwise returning false. This differs from the Collection.add method, which can fail to add an element only by throwing an unchecked exception. The offer method is designed for use when failure is a normal, rather than exceptional occurrence, for example, in fixed-capacity (or \"bounded\") queues.\n\nWhen using a capacity-restricted queue, offer() is generally preferable to add(), which can fail to insert an element only by throwing an exception. And PriorityQueue is an unbounded priority queue based on a priority heap." } ]
208-stackexchange
[ { "from": "human", "value": "I've looked in the Apex developer's guide and a saw the Naming Conventions section which has basically only has this:\n\nWe 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.\n\nI'm looking for something more in depth, such as end all Controllers with Controller and their tests with ControllerTest, etc.\nWhat is a good set of naming conventions to use when developing on the Force.com platofrm? It would be preferable if the answer has something that handles custom objects, classes, visualforce pages, and components and not just Apex classes." }, { "from": "gpt", "value": "Follow the CamelCase Java conventions, except for VF pages and components start with a lower case letter.\n\nTriggers:\n* <ObjectName>Trigger - The trigger itself. One per object.\n* <ObjectName>TriggerHandler - Class that handles all functionality of the trigger\n* <ObjectName>TriggerTest\n\nControllers:\n* <ClassName>Controller\n* <ClassName>ControllerExt\n* <ClassName>ControllerTest\n* <ClassName>ControllerExtTest\n\nClasses:\n* <ClassName>\n* <ClassName>Test (These might be Util classes or Service classes or something else).\n\nVisualforce pages and components:\n* <ControllerClassName>[optionalDescription] (without the suffix Controller). There might be multiple views so could also have an extra description suffix.\n\nObject Names and custom Fields\n* Upper_Case_With_Underscores\n\nVariables/properties/methods in Apex\n* camelCaseLikeJava - more easily differentiated from fields\n\nTest methods in test classes\n* test<methodOrFunctionalityUnderTest><ShortTestCaseDesc> - For example, testSaveOpportunityRequiredFieldsMissing, testSaveOpportunityRequiredFieldsPresent, etc.\n\nWorking on something that would be used as an app or in some cases just a project? If yes, then do the following:\n\nPrefix all custom objects, apex classes, Visualforce pages and components with an abbreviation so that they are easier to identify (e.g., easier for changesets). For example the WidgetFactory app would have the prefix wf on those. Additionally, when adding custom fields to a standard object they would also be prefixed to identify them as part of the app/package.\n\nThe main reason for the Object and Fields Names using Upper_Case_With_Underscores is that when you type in the name field or object with spaces it automatically adds the underscores. Although Apex is case insensitive, always refer to the Objects and Custom Fields in the code as Upper_Case_With_Underscores as well for consistency all around and consistency with what is generated by the SOQL schema browser and other tools. Object and Field Labels (which are generally ignored by code but visible to users) should keep spaces, not underscores." } ]
209-stackexchange
[ { "from": "human", "value": "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 about it a little more I suppose I can kind of see how it makes sense.\nThis makes me wonder: Is this a common pattern in other languages? Especially ones not closely related to English." }, { "from": "gpt", "value": "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 originally used to define that Sprachbund in the first place!\n\nThe construction seems to have arisen back in Latin. In Classical Latin, past aoristic verbs (\"I loved\") and present perfective verbs (\"I have loved\") look exactly the same: both of those would be written amāvī. But it's a pretty useful distinction to be able to make! So in Vulgar Latin, a new construction arose, using the verb habēre (\"to have\"). It's thought that a phrase like habeō litterās scriptās \"I have (written letters)\" got reanalyzed into \"I (have written) letters\", with habēre no longer indicating that you're actually holding anything in your hands, just that an action's been completed in the past.\n\nVulgar Latin eventually evolved into French, Italian, Spanish, and all the other Romance languages, and brought this construction with it; habēre is the direct ancestor of French avoir, via a series of sound changes. And once various Romance languages and Germanic languages and others were all being spoken in the same area, this feature spread through the Sprachbund: people speaking Germanic languages started to use the same construction. English \"have\"/German haben/etc isn't actually at all related to Latin habēre, but they looked similar, so it was the obvious choice when adopting the construction into Germanic.\n\nNowadays, this feature is called the \"have-perfective\", and it shows up in all sorts of languages within the Standard Average European (SAE) Sprachbund. It's not at all universal, but can be a good way to determine if a language has been influenced by SAE or not!" } ]
210-stackexchange
[ { "from": "human", "value": "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 relative to the current working directory. Is there a way to specify that this relative url is from the location of the script instead?" }, { "from": "gpt", "value": "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.\nSo we have 3 paths here (possibly duplicated):\n\n* ```mod_path```: which is the path of the simple helper script\n* ```src_path```: which contains a couple of template files waiting to be copied.\n* ```cwd```: current directory, the destination of those template files.\n\nand the problem is: we don't have the full path of ```src_path```, only know it's relative path to the ```mod_path```.\nNow let's solve this with the the amazing ```pathlib```:\n```# Hope you don't be imprisoned by legacy Python code :)\nfrom pathlib import Path\n# `cwd`: current directory is straightforward\ncwd = Path.cwd()\n# `mod_path`: According to the accepted answer and combine with future power\n# if we are in the `helper_script.py`\nmod_path = Path(__file__).parent\n# OR if we are `import helper_script`\nmod_path = Path(helper_script.__file__).parent\n# `src_path`: with the future power, it's just so straightforward\nrelative_path_1 = 'same/parent/with/helper/script/'\nrelative_path_2 = '../../or/any/level/up/'\nsrc_path_1 = (mod_path / relative_path_1).resolve()\nsrc_path_2 = (mod_path / relative_path_2).resolve()\n```\nIn the future, it's just that simple.\n\nMoreover, we can select and check and copy/move those template files with ```pathlib```:\n```if src_path != cwd:\n # When we have different types of files in the `src_path`\n for template_path in src_path.glob('*.ini'):\n fname = template_path.name\n target = cwd / fname\n if not target.exists():\n # This is the COPY action\n with target.open(mode='wb') as fd:\n fd.write(template_path.read_bytes())\n # If we want MOVE action, we could use:\n # template_path.replace(target)\n```" } ]
211-stackexchange
[ { "from": "human", "value": "How to send HTML-formatted email in C#?" }, { "from": "gpt", "value": "Setting isBodyHtml to true allows you to use HTML tags in the message body:\n```\nmsg = new MailMessage(\"[email protected]\",\n \"[email protected]\", \"Message from PSSP System\",\n \"This email sent by the PSSP system<br />\" +\n \"<b>this is bold text!</b>\");\n\nmsg.IsBodyHtml = true;\n```" } ]
212-stackexchange
[ { "from": "human", "value": "I want to sum a list of Integers. It works as follows, but the syntax does not feel right. Could the code be optimized?\n```Map integers;\nintegers.values().stream().mapToInt(i -> i).sum();\n```" }, { "from": "gpt", "value": "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:\n```\nintegers.values().stream().mapToInt(i -> i.intValue()).sum();\nintegers.values().stream().mapToInt(Integer::intValue).sum();\n```\nThe other simple option is `BigDecimal sum = numbers.stream().reduce(BigDecimal.ZERO, BigDecimal::add);`." } ]
213-stackexchange
[ { "from": "human", "value": "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?" }, { "from": "gpt", "value": "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.\nFor example ```\\mbox{..}``` is defined as ```\\leavevmode\\hbox{..}``` to ensure that horizontal mode is entered if it is used at the beginning of a paragraph. If you only use ```\\hbox{ }``` it is stacked above the following paragraph instead.\nCompare:\n```Text\\par\\hbox{Hello} World\n```\nResult:\n``` Text\nHello\n World\n```\nwith:\n```Text\\par\\mbox{Hello} World\n```\nResult:\n``` Text\n Hello World\n```\nYou see that in the first case the ```\\hbox``` is stacked with the two paragraphs vertically (but without paragraph indention) because it is processed in vertical mode. In the second case horizontal mode is entered first and so ```Hello``` is processed as part of the second paragraph.\n\n Use ```\\leavevmode``` for all macros which could be used at the begin of the paragraph and add horizontal boxes by themselves (e.g. in form of text).\n\nFor further reading about ```\\leavevmode``` please see \"The TeXBook\" by Donald E. Knuth, Appendix A, section 13.1, page 313 as well Appendix B, page 356." } ]
214-stackexchange
[ { "from": "human", "value": "In Python specifically, how do variables get shared between threads?\nAlthough 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 storage to avoid this sharing?\nI have seen many warnings about synchronizing access to shared data among threads by using locks but I have yet to see a really good example of the problem. \nThanks in advance!" }, { "from": "gpt", "value": "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, and anything can refer to them. The `Thread` object for a particular thread is not a special object in this regard. If you store the `Thread` object somewhere all threads can access (like a global variable) then all threads can access that one Thread object. If you want to atomically modify anything that another thread has access to, you have to protect it with a lock. And all threads must of course share this very same lock, or it wouldn't be very effective.\n\nIf you want actual thread-local storage, that's where `threading.local` comes in. Attributes of `threading.local` are not shared between threads; each thread sees only the attributes it itself placed in there. If you're curious about its implementation, the source is in _threading_local.py in the standard library." } ]
215-stackexchange
[ { "from": "human", "value": "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.\nAfter two decades I still can't figure out why dictators, like Kim Jong-un for example, ban people from leaving their home countries?\nCould it be that a dictator is usually interested in looting the country he rules, and having a smaller population means more natural resources for him and fewer protesters?" }, { "from": "gpt", "value": "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 gathering and assembling the resources the regime needs. Additionally, the regime especially does not want people with access to sensitive information to defect to their enemies. That isn't just spies and soldiers, there are plenty of \"regular\" government positions that require access to something the regime would not want falling into enemy hands, like economic data that could be used for propaganda. Obviously this is true of any country, and even in democracies with strong human rights records, people with access to classified information are usually required to submit to strict scrutiny of their international travel. Given that they aren't concerned with human rights, dictatorships can take the easier option of restricting travel to any citizens.\nHowever, defection is really a piece of a bigger issue - oppressive regimes maintain their rule in part by controlling information. Here's an interesting article that talks about how dictatorships keep power. Jerrold Post, director of the political psychology program at George Washington University, is referenced:\n\n Post said that in both Iraq and North Korea, dictators tightly controlled the flow of information. That control was upended in the past two years during the \"Arab spring\" revolts that swept away despots in Tunisia, Egypt, Libya and some of the Gulf states, revolts that were encouraged in large part by information spread by cell phones and social media. \n\nNorth Korea is probably the most extreme example of information control (according to Reporters without Borders, they are dead last in Press Freedom in the world), but this can be seen in other oppressive regimes - for example, China attempts to limit access to \"wrong\" information via its Great Firewall. This is thrown out the window if citizens go somewhere with free media and realize they are being lied to. Traveling can be the cause of their dissension, rather than a symptom.\nKnown dissidents may also be restricted from traveling so that they can not coordinate with foreign countries or anti-dictatorship organizations, and to prevent them from smuggling contraband or evidence of the regime's misinformation back into the country. Regimes can control the information originating in their country, but once someone is outside their borders the regime cannot control who they speak with." } ]
216-stackexchange
[ { "from": "human", "value": "Why can't we kill ourselves by holding our breath?" }, { "from": "gpt", "value": "## Short answer\nHealthy people cannot hold their breaths until unconsciousness sets in, let alone commit suicide.\n\n## Background\nAccording to Parkes (2005), a normal person cannot even hold their breath to unconsciousness, let alone death. Parkes says:\n\n Breath‐holding is a voluntary act, but normal subjects appear unable\n to breath‐hold to unconsciousness. A powerful involuntary mechanism\n normally overrides voluntary breath‐holding and causes the breath that\n defines the breakpoint.\n\nParkes explains that voluntary breath‐holding does not stop the central respiratory rhythm. Instead, breath holding merely suppresses its expression by voluntarily holding the chest at a certain volume. At the time of writing, no simple explanation for the break point existed. It is known to be caused by partial pressures of blood gases activating the carotid arterial chemoreceptors. They are peripheral sensory neurons that detect changes in chemical concentrations, including low oxygen (hypoxia) and high carbon dioxide (hypercapnia). Both hypoxia and hypercapnia are signs of breath holding and both are detected by the chemoreceptors. These receptors send nerve signals to the vasomotor center of the medulla which eventually overrides the conscious breath holding.\n\nThe breaking point can be postponed by large lung inflations, hyperoxia and hypocapnia, and it is shortened by increased metabolic rates.\n\nReference\n- Parkes, Exp Physiol (2006); 91(1): 1-15" } ]
217-stackexchange
[ { "from": "human", "value": "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, &quot;The car is giving an amazing mileage&quot;.\nAnd I am like, what does that water dripping mean even then? Why does the water drip? What is the source of it? And what does it signify?" }, { "from": "gpt", "value": "It signifies that the car is running absolutely correct. Here is the reason why:\n\nA gasoline (petrol) molecule is made up as such:\n\nC8H18 (or 8 Carbon atoms and 18 Hydrogen atoms)\n\nEnergy is obtained from the combustion of it by the conversion of a hydrocarbon to carbon dioxide and water. The combustion of octane follows this reaction:\n\n 2 C8H18 + 25 O2 → 16 CO2 + 18 H2O\n\nOr better said, you have two of the hydrocarbon molecules along with 25 oxygen molecules, they swirl together into a mix, the spark plug ignites them, boom, and out the tail pipe comes 16 carbon dioxide molecules and 18 water molecules ... at least in a perfect world. Some cars don't put out exactly that ratio. There may be a little bit of carbon monoxide (CO), unburnt hydrocarbons (C8H18), and/or nitrogen oxide (NO2) coming out of the engine exhaust port along with the CO2 and H2O. In this case, the catalytic convertor's job is to help clean these up so you can get closer to the perfect ratio described above.\n\nAs described, the water coming out of the tail pipe is a natural occurrence of the combustion process. You will usually see it coming out of the tail pipe when the engine and exhaust system of the vehicle is not completely warmed up. When it does become completely warmed up, you won't see it any more, because it comes out as steam (well, you'll see it in the winter time if it's cold enough, but you get the idea). " } ]
218-stackexchange
[ { "from": "human", "value": "Why can't MX records point to an IP address?" }, { "from": "gpt", "value": "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 an unqualified domain name, which cannot be resolved.\n\nThe reasons for this in the 1980s, when the specs were originally written, are almost the same as the reasons for it today: A host may be connected to multiple networks and use multiple protocols.\n\nBack in the 80s, it was not uncommon to have mail gateways which connected both to the (relatively new) Internet which used TCP/IP and to other legacy networks, which often used other protocols. Specifying MX in this way allowed for DNS records which could identify how to reach such a host on a network other than the Internet, such as Chaosnet. In practice, though, this almost never happened; virtually everyone re-engineered their networks to become part of the Internet instead.\n\nToday, the situation is that a host may be reached by multiple protocols (IPv4 and IPv6) and by multiple IP addresses in each protocol. A single MX record can't possibly list more than one address, so the only option is to point to a host, where all of that host's addresses can then be looked up. (As a performance optimization, the DNS server will send along the address records for the host in the response additional section if it has authoritative records for them, saving a round trip.)\n\nThere is also the situation that arises when your mail exchangers are provided by a third party (e.g. Google Apps or Office 365). You point your MX records to their hostnames, but it may occur that the service provider needs to change the mail servers' IP addresses. Since you have pointed to a host, the service provider can do this transparently and you don't have to make any changes to your records." } ]
219-stackexchange
[ { "from": "human", "value": "Why is ```SELECT *``` bad practice? Wouldn't it mean less code to change if you added a new column you wanted?\nI understand that ```SELECT COUNT(*)``` is a performance problem on some DBs, but what if you really wanted every column?" }, { "from": "gpt", "value": "The asterisk character, \"*\", in the SELECT statement is shorthand for all the columns in the table(s) involved in the query. \nPerformance\nThe ```*``` shorthand can be slower because:\n\n* Not all the fields are indexed, forcing a full table scan - less efficient\n* What you save to send ```SELECT *``` over the wire risks a full table scan\n* Returning more data than is needed\n* Returning trailing columns using variable length data type can result in search overhead\n\nMaintenance\nWhen using ```SELECT *```:\n\n* Someone unfamiliar with the codebase would be forced to consult documentation to know what columns are being returned before being able to make competent changes. Making code more readable, minimizing the ambiguity and work necessary for people unfamiliar with the code saves more time and effort in the long run.\n* If code depends on column order, ```SELECT *``` will hide an error waiting to happen if a table had its column order changed.\n* Even if you need every column at the time the query is written, that might not be the case in the future\n* the usage complicates profiling\n\nDesign\n```SELECT *``` is an anti-pattern:\n\n* The purpose of the query is less obvious; the columns used by the application is opaque\n* It breaks the modularity rule about using strict typing whenever possible. Explicit is almost universally better. \n\nWhen Should \"SELECT *\" Be Used?\nIt's acceptable to use ```SELECT *``` when there's the explicit need for every column in the table(s) involved, as opposed to every column that existed when the query was written. The database will internally expand the * into the complete list of columns - there's no performance difference.\nOtherwise, explicitly list every column that is to be used in the query - preferably while using a table alias." } ]
220-stackexchange
[ { "from": "human", "value": "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 airport, they have a variety of landing fees, ramp fees, and prior-approval requirements.\nBut later, I moved near MCI, and was told that landing at the big airport was no big deal. That they're actually happy to have little planes there.\nIf you fly small GA planes, do you land at the major airports in your area?\nWhat advanced preparations can you make to minimize your impact on the \"big boys\", and remain a good airspace citizen?" }, { "from": "gpt", "value": "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 that it works.\n\nVery often, there are multiple runways at bigger airports, and sometimes there are even shorter runways that are dedicated for airplanes that don't need to land on the same one as the \"big boys\". Even if not, they will work you in.\n\nNow, that being said, very often there is a better option. As you said, there are usually high fees at the big airports, so landing at a smaller satellite airport can often save you money and save you time because you won't have to taxi as far or sit and wait in line to get out. An extra 15 minutes by car can be better than an extra 30 minutes while taxiing. \n\nAs far as being prepared, it isn't really much different than smaller airports other than the fact that ATC is much busier. They don't have the time/tolerance to keep repeating instructions to you, and expect you to be \"on your game\". When they rattle off taxi instructions like \"Cessna N1234, taxi to the ramp via Alpha, Tango, Echo, and Xray. Hold short of runway 23.\" they expect a quick readback and for you to follow instructions exactly because they need to move on to the next guy. \n\nIt will also help everyone out if you don't fly your final approach the way that most people are taught for an entire 10 mile final: very close to your actual landing speed. In fact, you are usually landing on a runway that is 4X+ the distance that you need and you can slow down fairly quickly (especially compared to a jet), so if you can fly an extra 20 (or 80) knots as long as possible, it will be greatly appreciated and keep traffic moving. Make sure that you leave yourself enough time to slow down at the end and above all else, ***be safe***." } ]
221-stackexchange
[ { "from": "human", "value": "I need a way to compare multiple strings to a test string and return the string that closely resembles it:\n```TEST STRING: THE BROWN FOX JUMPED OVER THE RED COW\nCHOICE A : THE RED COW JUMPED OVER THE GREEN CHICKEN\nCHOICE B : THE RED COW JUMPED OVER THE RED COW\nCHOICE C : THE RED FOX JUMPED OVER THE BROWN COW\n```\n(If I did this correctly) The closest string to the \"TEST STRING\" should be \"CHOICE C\". What is the easiest way to do this?\nI plan on implementing this into multiple languages including VB.net, Lua, and JavaScript. At this point, pseudo code is acceptable. If you can provide an example for a specific language, this is appreciated too!" }, { "from": "gpt", "value": "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 implementation in VBA involves a weighted comparison of the length of the two phrases, the number of changes between each phrase, and whether each word could be found in the target entry.\n\n```\n'Calculate the Levenshtein Distance between two strings (the number of insertions,\n'deletions, and substitutions needed to transform the first string into the second)\nPublic Function LevenshteinDistance(ByRef S1 As String, ByVal S2 As String) As Long\n Dim L1 As Long, L2 As Long, D() As Long 'Length of input strings and distance matrix\n Dim i As Long, j As Long, cost As Long 'loop counters and cost of substitution for current letter\n Dim cI As Long, cD As Long, cS As Long 'cost of next Insertion, Deletion and Substitution\n L1 = Len(S1): L2 = Len(S2)\n ReDim D(0 To L1, 0 To L2)\n For i = 0 To L1: D(i, 0) = i: Next i\n For j = 0 To L2: D(0, j) = j: Next j\n\n For j = 1 To L2\n For i = 1 To L1\n cost = Abs(StrComp(Mid$(S1, i, 1), Mid$(S2, j, 1), vbTextCompare))\n cI = D(i - 1, j) + 1\n cD = D(i, j - 1) + 1\n cS = D(i - 1, j - 1) + cost\n If cI <= cD Then 'Insertion or Substitution\n If cI <= cS Then D(i, j) = cI Else D(i, j) = cS\n Else 'Deletion or Substitution\n If cD <= cS Then D(i, j) = cD Else D(i, j) = cS\n End If\n Next i\n Next j\n LevenshteinDistance = D(L1, L2)\nEnd Function\n```\n\nWe can creat two separate metrics for evaluating the similarity of two strings. One is \"valuePhrase\" and the other is \"valueWords\". valuePhrase is just the Levenshtein distance between the two phrases, and valueWords splits the string into individual words, based on delimiters such as spaces, dashes, and anything else you'd like, and compares each word to each other word, summing up the shortest Levenshtein distance connecting any two words. Essentially, it measures whether the information in one 'phrase' is really contained in another, just as a word-wise permutation.\n\nvalueWords, valuePhrase, and Split function:\n```\nPublic Function valuePhrase#(ByRef S1$, ByRef S2$)\n valuePhrase = LevenshteinDistance(S1, S2)\nEnd Function\n\nPublic Function valueWords#(ByRef S1$, ByRef S2$)\n Dim wordsS1$(), wordsS2$()\n wordsS1 = SplitMultiDelims(S1, \" _-\")\n wordsS2 = SplitMultiDelims(S2, \" _-\")\n Dim word1%, word2%, thisD#, wordbest#\n Dim wordsTotal#\n For word1 = LBound(wordsS1) To UBound(wordsS1)\n wordbest = Len(S2)\n For word2 = LBound(wordsS2) To UBound(wordsS2)\n thisD = LevenshteinDistance(wordsS1(word1), wordsS2(word2))\n If thisD < wordbest Then wordbest = thisD\n If thisD = 0 Then GoTo foundbest\n Next word2\nfoundbest:\n wordsTotal = wordsTotal + wordbest\n Next word1\n valueWords = wordsTotal\nEnd Function\n\n''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n' SplitMultiDelims\n' This function splits Text into an array of substrings, each substring\n' delimited by any character in DelimChars. Only a single character\n' may be a delimiter between two substrings, but DelimChars may\n' contain any number of delimiter characters. It returns a single element\n' array containing all of text if DelimChars is empty, or a 1 or greater\n' element array if the Text is successfully split into substrings.\n' If IgnoreConsecutiveDelimiters is true, empty array elements will not occur.\n' If Limit greater than 0, the function will only split Text into 'Limit'\n' array elements or less. The last element will contain the rest of Text.\n''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\nFunction SplitMultiDelims(ByRef Text As String, ByRef DelimChars As String, _\n Optional ByVal IgnoreConsecutiveDelimiters As Boolean = False, _\n Optional ByVal Limit As Long = -1) As String()\n Dim ElemStart As Long, N As Long, M As Long, Elements As Long\n Dim lDelims As Long, lText As Long\n Dim Arr() As String\n\n lText = Len(Text)\n lDelims = Len(DelimChars)\n If lDelims = 0 Or lText = 0 Or Limit = 1 Then\n ReDim Arr(0 To 0)\n Arr(0) = Text\n SplitMultiDelims = Arr\n Exit Function\n End If\n ReDim Arr(0 To IIf(Limit = -1, lText - 1, Limit))\n\n Elements = 0: ElemStart = 1\n For N = 1 To lText\n If InStr(DelimChars, Mid(Text, N, 1)) Then\n Arr(Elements) = Mid(Text, ElemStart, N - ElemStart)\n If IgnoreConsecutiveDelimiters Then\n If Len(Arr(Elements)) > 0 Then Elements = Elements + 1\n Else\n Elements = Elements + 1\n End If\n ElemStart = N + 1\n If Elements + 1 = Limit Then Exit For\n End If\n Next N\n 'Get the last token terminated by the end of the string into the array\n If ElemStart <= lText Then Arr(Elements) = Mid(Text, ElemStart)\n 'Since the end of string counts as the terminating delimiter, if the last character\n 'was also a delimiter, we treat the two as consecutive, and so ignore the last elemnent\n If IgnoreConsecutiveDelimiters Then If Len(Arr(Elements)) = 0 Then Elements = Elements - 1\n\n ReDim Preserve Arr(0 To Elements) 'Chop off unused array elements\n SplitMultiDelims = Arr\nEnd Function\n```\n\nUsing these two metrics, and a third which simply computes the distance between two strings, we have a series of variables which we can run an optimization algorithm to achieve the greatest number of matches. Fuzzy string matching is, itself, a fuzzy science, and so by creating linearly independent metrics for measuring string similarity, and having a known set of strings we wish to match to each other, we can find the parameters that, for our specific styles of strings, give the best fuzzy match results.\n\nTo allow the optimization of fuzzy matching, we can weight each metric. The formula that defines the final score is a simply combination of the metrics and their weights: \n```\nvalue = Min(phraseWeight*phraseValue, wordsWeight*wordsValue)*minWeight\n + Max(phraseWeight*phraseValue, wordsWeight*wordsValue)*maxWeight\n + lengthWeight*lengthValue\n```\n\nFor your specific context, you have to come up with a set of weights for any metrics you come up with to determine similarity. With the appropriate set of heuristics and weights, you'll have your comparison program quickly making the decisions that you would have made." } ]
222-stackexchange
[ { "from": "human", "value": "Given the following code:\n```var arr = [1,2,3,4,5];\nvar results: number[] = await arr.map(async (item): Promise => {\n await callAsynchronousOperation(item);\n return item + 1;\n });\n```\nwhich produces the following error:\n\n TS2322: Type 'Promise[]' is not assignable to type 'number[]'.\n Type 'Promise is not assignable to type 'number'.\n\nHow can I fix it? How can I make ```async await``` and ```Array.map``` work together?" }, { "from": "gpt", "value": "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.\nWhen 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 Promise objects) here instead of a Promise, the value returned by await is simply that array, which is of type ```Promise[]```.\nWhat you probably want to do is call ```Promise.all``` on the array returned by ```map``` in order to convert it to a single Promise before ```await```ing it.\nAccording to the MDN docs for ```Promise.all```:\n\nThe ```Promise.all(iterable)``` method returns a promise that resolves\nwhen all of the promises in the iterable argument have resolved, or\nrejects with the reason of the first passed promise that rejects.\n\nSo in your case:\n```var arr = [1, 2, 3, 4, 5];\nvar results: number[] = await Promise.all(arr.map(async (item): Promise => {\n await callAsynchronousOperation(item);\n return item + 1;\n}));\n```\nThis will resolve the specific error you are encountering here.\nDepending on exactly what it is you're trying to do you may also consider using ```Promise.allSettled```, ```Promise.any```, or ```Promise.race``` instead of ```Promise.all```, though in most situations (almost certainly including this one) ```Promise.all``` will be the one you want." } ]
223-stackexchange
[ { "from": "human", "value": "Why don't helicopters use reaction wheels to counter the main rotor?" }, { "from": "gpt", "value": "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.\n\nYou propose instead to impart an opposite torque through a reaction wheel. That would indeed impart an opposite torque for short lengths of time. However, you don't get a torque from spinning a reaction wheel at constant angular velocity but by changing and accelerating that angular velocity.\n\nNow the torque imparted on the helicopter by the air through the main rotor is steady - or at least its of roughly constant direction. Therefore, to counter that torque, the reaction wheel would have to accelerated uniformly and indefinitely. Clearly this is impossible from an engineering standpoint.\n\nYou can also think of this from a conservation of angular momentum, without thinking about the origin of the torques. The air imparts a steady angular impulse to the helicopter. Therefore, the helicopter system's angular momentum must increase steadily (unless there's a countering torque from the tailfan). So either that angular momentum is the spinning of the helicopter's body (which is what we're trying to avoid) or that of the reaction wheel, whose angular momentum must be steadily increasing under the action of the angular impulse to the system." } ]
224-stackexchange
[ { "from": "human", "value": "When configuring cron to run a command every other day using the \"Day of Month\" field, like so: \n```1 22 */2 * * COMMAND\n```\nit runs every time the day of month is odd: 1,3,5,7,9 and so on.\nHow 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 problematic as every month has a different number of days in the month)?" }, { "from": "gpt", "value": "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 range and using either an odd or even number of days. Since even day scripts would never run on the 31st day of longer months, you don't lose anything using 30 days as the base for even-days, and by specifying specifically to divide it up as if there were 31 days you can force odd-day execution.\n\nThe syntax would look like this:\n```# Will only run on odd days:\n0 0 1-31/2 * * command\n# Will only run on even days:\n0 0 2-30/2 * * command\n```\n\nYour concern about months not having the same number of days is not important here because no months have MORE days than this, and for poor February, the date range just won't ever match the last day or two, but it will do no harm having it listed.\n\nThe only 'gotcha' for this approach is that if you are on an odd day cycle, following months with 31 days your command will also run on the first of the month. Likewise if you are forcing an even cycle, each leap year will cause one three-day cycle at the end of February. You cannot really get around the fact that any regular pattern of \"every other day\" is not always going to fall on even or odd days in every month and any way you force this you will either have an extra run or be missing a run between months with mismatched day counts." } ]
225-stackexchange
[ { "from": "human", "value": "Is there a way to have a private setter for a property in TypeScript?\n```class Test\n{\n private _prop: string;\n public get prop() : string\n {\n return this._prop;\n }\n private set prop(val: string)\n {\n //can put breakpoints here\n this._prop = val;\n }\n}\n```\nCompiler complains that visibility for getter and setter don't match. I know I can just set the backing field, but but then I can't set breakpoints when the value is set.\nI though about using an interface to hide the setter, but interfaces can only define a property, not whether it has a getter on setter.\nAm I missing something here? There doesn't seem to be any reason to not allow private setters, the resulting JS doesn't enforce visibility anyway, and seems better that the current alternatives.\nAm I missing something? If not is there a good reason for no private setters?" }, { "from": "gpt", "value": "The TypeScript specification (8.4.3) says\"\n\n Accessors for the same member name must specify the same accessibility\n\nSo you have to choose a suitable alternative. Here are two options for you:\nYou can just not have a setter, which means only the ```Test``` class is able to set the property. You can place a breakpoint on the line ```this._prop =...```.\n```class Test\n{\n private _prop: string;\n public get prop() : string\n {\n return this._prop;\n }\n doSomething() {\n this._prop = 'I can set it!';\n }\n}\nvar test = new Test();\ntest._prop = 'I cannot!';\n```\nProbably the ideal way to ensure private access results in something akin to a \"notify property changed\" pattern can be implemented is to have a pair of private get/set property accessors, and a separate public get property accessor.\n\nYou still need to be cautious about someone later adding a direct call to the backing field. You could get creative in that area to try and make it less likely.\n```class Test\n{\n private _nameBackingField: string;\n private get _name() : string\n {\n return this._nameBackingField;\n }\n private set _name(val: string)\n {\n this._nameBackingField = val;\n // other actions... notify the property has changed etc\n }\n public get name(): string {\n return this._name;\n }\n doSomething() {\n this._name += 'Additional Stuff';\n }\n}\n```" } ]
226-stackexchange
[ { "from": "human", "value": "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.\nHow does learning vocabulary through sentences, thus giving context to the used words, compare to learning to recognize words alone? For example, the context may give away the meaning of the problematic vocabulary. Are there studies or expert opinions on one approach being preferable to the other at different stages of language learning? Or is it recommended that they be mixed for best results?" }, { "from": "gpt", "value": "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. \n\nWith vocabulary learning, using just one strategy is probably the least efficient. This is because every strategy has certain strengths (certain skills it builds well) and certain weaknesses (skills it doesn't cover well)- and if you keep using one strategy, you'll be only focusing on the strengths (but with diminishing returns), and not addressing the weaknesses.\n\nUsing flashcards helps you establish word-to-meaning equivalences quickly, but it usually does so with a shallow meaning, ignoring the breadth of meaning that words usually have. It also ignores the contextual subtleties of the word, and the knowledge is not always retained long-term. \n\nIt's best to combine flashcards with other strategies that will help you see how the word is used in context, show you the variety of meanings it can have (and doesn't have), see what collocations the word has, etc. One way of doing this is by reading examples of the word and writing your own sample sentences. Another important thing is to be exposed to the word in natural settings - so it's important to read a lot so that you'll encounter the words you've learnt naturally." } ]
227-stackexchange
[ { "from": "human", "value": "Can I spend the night alone in a tent in a forest outside Stockholm in -20°C without risking my life?\n\nThe backstory\nFrom 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 a will to try something new.)\nI do have friends who I could visit once a week or so to prepare food and wash my clothes, so I think I can solve the practical problems, or at least those that I've come to think of. I'd camp in one of the forests, maybe 1 km from \"civilisation\". I'd have access to showers etc at university every day.\nHowever: I don't want to freeze to death in my sleep! That's very important to me. I've read that the nights can get as cold as -20°C (-4°F). With the proper preparations, would this be a plausible way of living, at least for a month or so?\nI do have camping experience, and have been hiking for three weeks, but only in summer." }, { "from": "gpt", "value": "Yes, it is definitely doable. -20&deg;C is only -4&deg;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.\n\nFirst, your fear of dying of cold in your sleep is silly. You'd have to do something pretty stupid to die of hypothermia, and even that's not going to happen when you're inside the sleeping bag. The main danger will be from frostbite, but that again would largely need stupidity to help it along, although that's easier to do than outright death from hypothermia.\n\nYour tent will be a long term fixed installation you set up once at a time and conditions of your choosing. You can therefore afford a larger and heavier tent with more stuff you bring in once. Definitely get a tent you can stand upright in. That will make changing clothes much quicker and more comfortable. Since you should be able to keep water out of the tent, get a nice down sleeping bag and a few light blankets. The down bag should be rated for most nights, then put the blankets on top for the few unusually cold nights. Since again weight is not really a issue, get a full sleeping bag, not a mummy bag. They are simply more comfortable. Get a good insulating pad, and another two as backup. Get a tent large enough to fit your sleeping bag and something to sit on next to it, like a folding chair. Put something under the legs to spread out the weight to that they don't hurt the tent floor. Get one of those rubber-backed mats people sometimes put just inside their doors and put it just inside your tent. That allows a place to step with boots still on, then you can sit down on the chair with boots still on the mat to take them off. The crud stays on the mat, which you can shake clean by reaching outside after having put on your down hut booties.\n\nSome things are going to be a hassle. At -4&deg;F you want to keep your gloves on whenever possible, but some tasks will be difficult that way. You end up taking your gloves on and off a lot, trading off efficiency with cold fingers. Get a pair of polypro glove liners. They are thin and still allow many tasks to be done, but provide at least a little insulation. Their main advantage is that any metal you touch won't immediately conduct the heet from your hand away. Touching bare metal at -4&deg;F is a good way to get frostbite.\n\nBe prepared for some discomfort no matter what equipment you have. The toughest part will be getting yourself out of the sleeping bag in the morning. You'll really have to will yourself to leave the warm comfort of the bag and get into the air at probably the coldest part of the day. At some point you'll have to change your clothes and get undressed in the process. That's going to be cold. It won't be cold long enough to be any real danger, so it's really a mindset issue to get over. Whether you can or not and are willing to push yourself in that way only you can say.\n\nYou say you have access to heated buildings during the day, so it would make things a lot simpler for you if you don't have to deal with cooking and eating at your camp. Perparing food outside in the cold takes a lot longer than in a heated kitchen, severly limits what you can do, and may also risk predator encounters depending on what is around your area in the winter." } ]
228-stackexchange
[ { "from": "human", "value": "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?" }, { "from": "gpt", "value": "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 etymological rules\". \n\nIn that same year, a committee of the British Association for the Advancement of Science began developing a coherent system of electrical units, the cgs system. Varley, a committee member, liked Clark's proposal, but he advocated adding a French name such as Ampere, to facilitate the international acceptance of the new units (\"I should like to introduce a French name into the list. We have Germany, England and Italy represented\"). For the same reason he may have pleaded for not distorting the French and German names. In addition, Varley objected to the galvat \"because Galvani discovered next to nothing\".\n\nLatimer Clark adapted the unit names in his 'Elementary treatise on electrical measurement' (1868). He changed ohma to ohm, and dropped the galvat. Maxwell acknowledged Clark's practical units and their names in his 'Treatise on electricity and magnetism' (1873). In 1881, at the International Electrical Congress in Paris), two French names, ampere and coulomb, were added. The diplomacy worked, and the new system of electrical units was adopted by all countries. The only units that kept the initial name distortion were the volt and the farad." } ]
229-stackexchange
[ { "from": "human", "value": "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?\n\n For example, the force exerted on a charge in motion in an uniform magnetic field.\n\nWhy is it so? Why does that force have to be a cross product of two vectors?\nIs it possible to come up with them when what we do is just observe the nature?" }, { "from": "gpt", "value": "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 \"multiplying\" vectors together arise in so many different contexts?\n\nThe fundamental answer (which unfortunately may not be very accessible if you're a new student) is that there are only two algebraically independent tensors that are invariant under arbitrary rotations in $n$ dimensions (we say that they are \"$\\mathrm{SO}(n)$ invariant\"). These are the Kronecker delta $\\delta_{ij}$ and the Levi-Civita symbol $\\epsilon_{ijk \\cdots}$. Contracting two vectors with these symbols yields the dot and cross products, respectively (the latter only works in three dimensions). Since the laws of physics appear to be isotropic (i.e. rotationally invariant), it makes sense that any physically useful method for combining physical quantities like vectors together should be isotropic as well. The dot and cross products turn out to be the only two possible multilinear options.\n\nWhy multilinear maps are so useful in physics is an even deeper and more fundamental question, but which answers to that question are satisfying is probably inherently a matter of opinion." } ]
230-stackexchange
[ { "from": "human", "value": "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:\n```\nThe Web Application Project mycompany.myapp.mywebproject is configured to use IIS. The Web Server 'http://localhost/MyWebApp could not be found.\n```\nI have not manually set up virtual directories for this web application. \nPer colleagues, Visual Studio should prompt me to create virtual directories but I am not getting prompted. \nI installed VS2010 before installing IIS on my dev machine. \nHere is my development machine setup:\n\n* Windows 7 Enterprise\n* Service Pack 1\n* 64 bit OS\n* Visual Studio 2010 Enterprise Service pack 1\n* IIS version 7.5\n" }, { "from": "gpt", "value": "When this happens the easiest solution is to make the virtual directory manually.\n\nFirst of all, you need to make sure you have the right version of ASP.Net installed and that you have installed the IIS extensions.\nTo do this, go to the relevant .net version's folder in C:\\(Windows)\\Microsoft.NET\\Framework\\(dotnetver)\\\n (substituting the bracketed folders for the right folders on your PC) and run this command\n```aspnet_regiis.exe -i\n```\nNext once that's run and finished, sometimes running\n```iisreset\n```\nfrom the command line helps, sometimes you don't need to.\n\nNext, go to your IIS Manager and find you localhost website and choose add a folder.\nBrowse to the folder in your project that contains the actual ASP.Net project and add that.\n\nFinally, right click on the folder you added and you should have an option that says 'convert to application' or 'create virtual directory' or something similar.\n\nPlease make sure the Virtual directory has the name 'MyWebApp'!! Reload your solution and it should work.\n\nGood luck!" } ]
231-stackexchange
[ { "from": "human", "value": "Why is it hard to draw people running in animes?" }, { "from": "gpt", "value": "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.\n\nWhy is that you ask? The answer lies in how these countries distribute their budget and time. \n\nWhile American animation often times may seem lacking in it's attention to detail, it makes up for it the quality of their animation. American animation often times meticulous and original in how they animate motion, though sometimes content is reused cyclically, the animation is painstakingly frame by frame. \n\nIn contrast, Japanese anime uses a lot of shortcuts (to save budget and meet deadlines). Typically long scenes feature only the mouth of a character (and maybe other minor features like a waving hair or glittering eyes) moving during delivery of key information/dialog, or the short burst of motion of some character in some an action pose against an animated, cyclic, and stylized background (I'm looking at you transformation scenes). Often times these uses of dramatic still-shots are done against patterned (or static illustrated) backgrounds, sometimes a few moving emotive icons (sweat drops, question marks, small chibi animated heads) will accompany a some sort of monologue. Admittedly both styles of animation reuse shots and sequences, but it's more noticeable in Japanese anime for various reason (e.g., not enough budget and/or manpower). This is why Japanese anime is typically labeled as \"lazy\" by American animators and enthusiasts.\n\nA typical walk cycle in animation consists of 8 keyframes typically:\n\nThe smoothness of an animation is typically determined by the framerate and amount of key frames in the animation. \nIn American animation, the animation is captured by shooting two frames of film per drawing at a rate of 24 frames per second (fps) to achieve the smooth motion of American animation. \nJapanese anime, while it also runs at an average 24 fps, typically captures their animation at a rate of three or four frames per drawing in order to save money and manpower. Though it varies depending on the studio and tools used (e.g 3DCG) with main objects in the foreground (typically characters) are animated at 8 to 12 fps, while background objects can be animated at as low as 6 to 8 fps.\n\nLets compare the difference between one walk cycle that is 8 frame to one that is 16 frames, both at 60 fps:\n \nNotice the 16 frame one is smoother, but slower while the 8 frame is faster, but choppier. This is because it takes the 16 frame animation twice as long, covering more frames, to go through one cycle than the 8 frame one.\nThe varying of frame rates can also be be used to depict the expansion and compression of time (think bullet time from The Matrix). However generally choppy animation is the result of not enough keyframes in your animation. More frames mean more and manpower and/or time, which ultimately means more money is required. Japanese anime production don't typically have as big of a budget compared to American productions (but there are exceptions), so they must make do with what they have and cut corners where they can (like Shaft did with the certain Bakemonogatari TV episodes)." } ]
232-stackexchange
[ { "from": "human", "value": "Malachi 4:5: \n\n 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\n\nJesus says in Matthew 11:14\n\n \"and if you are willing to believe their message, John is Elijah, whose coming was predicted\"\n\nJesus says in Mathew 17:12\n\n But I tell you, Elijah has already come, and they did not recognize him, but have done to him everything they wished. In the same way the Son of Man is going to suffer at their hands.”\n\nIt's pretty clear from the above verses that John was Elijah reincarnated.\nWouldn't the above verses imply that reincarnation is true? " }, { "from": "gpt", "value": "Faulty Premise #1: John the Baptist was a reincarnation of Elijah\n\nWhen 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). \nWhat Jesus more likely was saying in Matthew 11 is that John the Baptist was a prophet in the tradition of Elijah. Elijah was the greatest of the prophets (even if his disciple Elisha inherited a double portion of his spirit). All of the prophets that followed came in the name and spirit of Elijah, in the same way that some of Paul's letters apparently were created after his death. They were in the spirit and tradition even if not the actual man. \nNote also Elijah never died - he was taken up into heaven, and people thought he would return. As such, no Elijah was not being thought to have reincarnated- only returned. Elijah's return was long a part of Jewish custom. Even today, during a Passover sedar, a chair is left empty for Elijah. But again, since he did not die, Jews look for his return, not his reincarnation. \n\nFaulty Premise #2: The Jewish world view has any concept of reincarnation at all\n\nThe most basic rule of hermeneutics suggests that a text cannot mean what it could not mean to the original audience. If the Jews had no concept of reincarnation, then any interpretation that says it does has a very, very high bar to clear.\nIn his book The Gift of the Jews, Thomas Cahill advances the thesis that the primary distinctive philosophy of the Jews was precisely that history was not circular. Their linear idea of a human life was a departure from others and was an explicit rejection of reincarnation. As such, a text would need to be exceedingly explicit to a culture that rejected circular life patterns, and the obscure interpretation above (especially in light of the more obvious intepretation) simply doesn't hold water.\nFurthermore, the book of Hebrews - written to the people into which both Jesus and John the Baptist were born - explicitly reject reincarnation. As the writer points out in 9:27, \n\n It is appointed unto a man once to die and then the judgement.\n\nHere we do have an explicit rejection of reincarnation by the followers of Jesus. There is one death. There is one judgement. Hence, in any Christian worldview, you don't come back." } ]
233-stackexchange
[ { "from": "human", "value": "I see hugely varied performance depending on how many newlines there are in the file I'm visiting.\nHere's an example. I have two JSON files:\n```$ wget https://github.com/Wilfred/ReVo-utilities/blob/a4bdc40dd2656c496defc461fc19c403c8306d9f/revo-export/dictionary.json?raw=true -O one_line.json\n$ python -m json.tool pretty_printed.json\n```\nThese are two JSON files with the same content. ```one_line.json``` is 18MiB of JSON without any newlines. ```pretty_printed.json``` has newlines and whitespace added, making it 41MiB.\nHowever, the bigger file split over many lines is much faster to open in Emacs, both in Javascript mode and Fundamental mode.\nWhy does Emacs have such poor performance with long lines, since it's actually fewer bytes? Is there anything I can do to improve performance without reformatting the data outside of Emacs?" }, { "from": "gpt", "value": "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 display eats up a lot of time. You can get some additional information in, for example, the docstring of ```cache-long-line-scans``` (renamed ```cache-long-scans``` in 24.4).\n\nYou can try and see if setting ```bidi-paragraph-direction``` to ```left-to-right``` and setting ```bidi-inhibit-bpa``` (new in Emacs 27, see footnote 1) to ```t``` improves the speed for you (see footnote 2). This removes some significant contributors to line scans, but sadly not the only ones.\n\nThe best option is to add newlines. You can pipe a JSON file through e.g. ```python -c 'import json, sys ; json.dump(json.load(sys.stdin), sys.stdout, indent=2)'``` to add newlines and improve readability in general.\n\nFootnote 1: ```bidi-inhibit-bpa``` is new in Emacs 27. Setting it to ```t``` can have a noticeable (sometimes dramatic) effect in cases where (a) a physical line is very long, and (b) the line includes many parentheses and/or braces, especially if they are nested.\nFootnote 2: There is also ```bidi-display-reordering```, but this is only for internal/debugging purposes. Setting it to ```nil``` may improve performance, however that is an unsupported setting which may cause other problems, so it is not recommended. In Emacs 27, the combination of setting ```bidi-paragraph-direction``` and ```bidi-inhibit-bpa``` is a supported configuration which provides approximately the same performance boost." } ]
234-stackexchange
[ { "from": "human", "value": "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). \nHow can we estimate amount of time/work/resources needed to complete such a task? What margins of error should we assume?" }, { "from": "gpt", "value": "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 distributed... use a method that incorporates an optimistic guess, a pessimistic guess and heavily weights your best guess. \n\nEstimate, test, check, then revise and update your project schedule. The third or fourth revision of the estimates is usually about as accurate as you can hope for; your second estimate is far better than your first guess ... if possible, try to get a measure from an early trial of a similar or analogous task ... revise the estimate and revise your plan as soon as better data becomes available. \n\nIf your first estimate was too conservative, don't allow slack time to corrupt completion of succeeding tasks. If your first estimate was overly optimistic, make your adjustments EARLY and let your stakeholders and customers know. It's more important to be good at following up, to check your estimates and to competently communicate updates than it is to be a develop skill as an estimator of unfamiliar tasks." } ]
235-stackexchange
[ { "from": "human", "value": "Why is Nazi-Germany commonly referred to as \"The Third Reich\" in English? Why is reich not translated when Dritten (\"third\") is?\nAnd what is the English synonym of reich? Realm?\nAustria (Republik Österreich), Norway (Kongeriket Norge) and Sweden (Konungariket Sverige) all have reich (or the Norwegian/Swedish corresponding etymology related word) in their name and they all have English translations of their name." }, { "from": "gpt", "value": "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\". \n\nWiktionary quotes Busching, who in 1762 explained Reich as a German understanding of \"Eminence\", from the Latin Regnum, rather than an Empire or a Realm as other cultures would understand it. \n\nOne could see it as a word used in English, Russian, Portuguese and many other languages as a designation for any kind of German kingdom, empire or absolutism, similar to how one would address a foreigner according to their origin, e.g. Senor Martinez, Monsieur Aragon.\n\nCompare it to how many cultures, including the Germans, also use the word \"Commonwealth\" or \"Soviet Union\", despite the fact that Bavaria had formed its own Union of Soviets, the Räterepublik, during the Weimar Republic.\n\nIf you're interested in knowing when the word \"Third Reich\" came into usage, it is worth noting that during Fascist Germany, the country's official name was Das Deutsche Reich, and in the USA and UK it was usually referred to as Germany, Hitler's Germany, Berlin, Reich or, the most popular term, Nazi Germany. \n\n(Sources: Neville Chamberlain's declaration of war against Germany, headlines about Germany in newspapers like the NY Times or the Times, the Daily Mail's Lord Rothermere)\n\nIn Germany itself, the idea of a third Reich stemmed from the 19th century, where it was a popular philosophical theme in literature and theology. Writers like Johannes Schlaf, who wrote \"Das Dritte Reich\" in 1899, or the German translator of Ibsen's \"The Emperor and the Galilean\", popularized the idea of the imminent arrival of a thousand years of Christianity (a kind of positive apocalypse), which would follow a third \"Reich\". And they would quote Paul the Apostle and various saints, to make it clear that the third Reich would follow the heretic lex naturalis and the lex mosaica. \n\nNazi propagandists exploited this in their articles, making it sound as if the saints had had some sort of epiphany about Hitler and the Nazis.\n\nIn other words, the Third Reich began as an abstract idea of a Christian revolution, but was assumed by Nazi writers in order to bolster Hitler's popularity and justify the drastic and bloody decisions that the Fascist government was making.\n\nIn one of the earliest examples of the Third Reich being mentioned outside of Germany, Major Strasser in the film Casablanca talks about the Third Reich as if it was just the beginning to a kind of paradisaical future or of a fourth Reich.\n\nAfter 1945, the term was used exclusively to associate only to the unsuccessful reign of Fascism in Germany, and it ceased as a philosophical or theological idea in German literary circles." } ]
236-stackexchange
[ { "from": "human", "value": "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?" }, { "from": "gpt", "value": "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.\n\nChemically, paper is mainly composed of cellulose from plant fibers. Cellulose is an organic polymer, which has D-glucose units connected through hydrogen bonds. These bonds form between the oxygen atom of the one-hydroxyl group belonging to the glucose and the hydrogen atom of the next glucose unit. These are microscopic properties of paper, but to understand what happens when we fold paper or do Origami, it is sufficient to learn what is happening macroscopically.\n\nAll materials have what is called an elastic limit and a plastic region. The elastic limit is the point at which a material will bend but still return to its original position without any permanent change or damage to its structure. Further deforming the material beyond this limit takes it to its plastic region. At this point any structural or physical changes become permanent and the paper will not return to its original form.\n\nEvery material has a different elastic limit or yield, and plastic region. Imagine holding a piece of paper slightly bent but not folding or creasing it. The plant fibers that make up the paper will not have exceeded their elastic limit. So as soon as you let go of the paper sheet it will quickly return to its noncreased original flat state. However, if you were to roll that piece of paper into a cylinder and hold it for a few minutes, some of these fibers will be pushed beyond the elastic limit which is evident since it will not lie flat anymore since slight deformations have occurred in this sheet.\n\nNow, when you properly fold a piece of paper as you would during Origami, the plant fibers along the crease are pushed into the plastic region of the paper, causing a fracture point at the actual line of the fold. A practical example of this is if you were to fold a piece of paper, you will note that if you stretch the paper evenly on both sides of the fold, the paper will tear right on the fold (a quick way to &quot;cut&quot; paper if you have no scissors). The fold then becomes an irreversible structural failure and the fibers in the paper will never regain their original state.\n\nBecause of this damage to its structure, the paper will from then on have this fold. And no matter how hard you try to flatten out the fold it will never return to its original state. This is why Origami models continually retain their shape." } ]
237-stackexchange
[ { "from": "human", "value": "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): int```).\nOne of the advantages (for the parser, at least) for a ```fun``` keyword is that it lets the parser be context-free (it doesn't have to guess if ```int``` defines a variable or if it defines a function).\nWhen C was invented, computers had very little memory and speed (so little, that the reason C requires one to define all the variables in the beginning of the function was because it had to be a one-pass parser). Why didn't they choose the simple way out and use function defining keyword?" }, { "from": "gpt", "value": "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\"\n\nFor each object of such a composed type, there was already a way to mention the underlying object: index the array, call the function, use the indirection operator on the pointer. Analogical reasoning led to a declaration syntax for names mirroring that of the expression syntax in which the names typically appear. Thus,\n```int i, *pi, **ppi;\n```\ndeclare an integer, a pointer to an integer, a pointer to a pointer to an integer. The syntax of these declarations reflects the observation that ```i```, ```*pi```, and ```**ppi``` all yield an ```int``` type when used in an expression. Similarly,\n```int f(), *f(), (*f)();\n```\ndeclare a function returning an integer, a function returning a pointer to an integer, a pointer to a function returning an integer;\n```int *api[10], (*pai)[10];\n```\ndeclare an array of pointers to integers, and a pointer to an array of integers. In all these cases the declaration of a variable resembles its usage in an expression whose type is the one named at the head of the declaration.\n\n\nIt appears this rule trumped parser considerations. Its immediate consequence is that function declarations can’t use specific keywords, or impose a different ordering of declaration components.\nIt’s worth noting that parsing was somewhat different in early C, since function declarations didn’t specify their arguments, and function definitions separated the argument list from the argument declarations (which weren’t necessary for ```int``` arguments):\n```sum();\n```\ndeclares a ```sum``` function, which would then be defined as\n```sum(a, b) {\n return a + b;\n}\n```\n(no types needed here, the default is ```int```). So the parser didn’t deal with types inside argument lists." } ]
238-stackexchange
[ { "from": "human", "value": "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.\nAs of now I am using the 'L' - which is not good! :-( \nAny help?\nUPDATE The 2 best solutions are;\n```\\usepackage{ amssymb }\n\\mathcal{L}\n```\nand\n```\\usepackage{ mathrsfs }\n\\mathscr{L}\n```\nI got my answers at, http://detexify.kirelabs.org/classify.html " }, { "from": "gpt", "value": "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\n```\\newcommand{\\Lagr}{\\mathcal{L}}\n```\n\nThis way, if you ever decide that that curly L is not quite the one you like, it is easy to switch. Also, even before you knew the answer to this question, you could have written\n```\\newcommand{\\Lagr}{L}\n```\nin your preamble. Then you could start/continue writing the document, use ordinary capital Ls where you want, and ```\\Lagr``` wherever you actually mean a Lagrangian, and then later changing the definition of ```\\Lagr``` to something appropriate. This way, you wouldn't have to manually search for each occurence of a capital L and decide if it's a Lagrangian or not. Clearly ```\\Lagr``` (or whatever you want to call this macro) is also easier to type than ```\\mathcal{L}```, and it makes the source code much more readable.\n\nAnother advantage, which is probably more subtle, since you're new to LaTeX, is that we can make the curvy L exactly the type of math we want. TeX distinguishes between ordinary letters, binary operators, binary relations, opening and closing parenthesis and so on; the spacing between two ordinary letters is not the same as the spacing between the ```a```, ```+```, and ```b``` in ```$a+b$```. So since the Lagrangian is a kind of operator, we could say\n```\\newcommand{\\Lagr}{\\mathop{\\mathcal{L}}}\n```\n\nBut in the case of operators, the package amsmath (which you are most likely using; if not, you should) provides a somewhat better mechanism:\n```\\DeclareMathOperator{\\Lagr}{\\mathcal{L}}\n```\n\nAnother (related) tip: Even if you are using the same notation for two different things, it is best to make a separate macro for each. In this case you might have\n```\\DeclareMathOperator{\\Lagr}{\\mathcal{L}}\n\\DeclareMathOperator{\\Lapl}{\\mathcal{L}}\n```\nThe reason is the same as in the ```L``` vs. ```\\Lagr``` case above: If you at some point decide that using ```\\mathcal{L}``` for both is a bad idea, you would have to find each occurence of ```\\Lagr``` and figure out if it is really a Laplacian. Using macro names carrying semantic meaning is one of the great powers of TeX." } ]
239-stackexchange
[ { "from": "human", "value": "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. \nAnd when he is at home with me and doing something wrong, I try to stop him, he tries to repeat my words and shouts at me. He is copying the behavior of others, whether it's a good act or bad...\nPlease help me how to stop him from being a bully." }, { "from": "gpt", "value": "Welcome to the \"Terrible Two's\"! \n\nYour 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 will try and every success reinforces this.\nHe also comes across more limitations: The more he is able to do, the more often he is stopped.\n\nThe solution? It's already in your question:\nHe will copy what others do. So by all means, stay calm. No yelling, no fussing and - please! - no hitting. He has some learning (accepted behaviour like sharing) and some unlearning (no hitting or pushing) to do and needs your help. \n\n* When he throws a tantrum, either ignore him, or quietly remove him from the scene. Do not worry about others! Most likely they have had the same trouble with their kids or will some time ;-) \n* When he doesn't want to share yet - fine, he will learn. This can be practiced. Don't make him share, or he will resent it. Rather, teach him the benefits of sharing. Start with food, for example. Have a plate of cookies (or other favorite food), that's yours. He will likely demand some, but demanding doesn't get him a cookie. Asking nicely will! Explain, repeat. Then, switch roles. If he has cookies, ask him to share. If he does, praise him. Else - remind him next time when he wants your cookies that he didn't share. Share whenever possible: Having a bite from your plate, getting a piece off his. Repeat, repeat, repeat.... Same goes for objects. Ask him to \"please\" share a toy, \"play\" with it for a short moment, then return. Say \"Thank you\". He learns, that he gets the toy back. Share some of your things. (Monitor the behaviour of other children, that want his toys - make sure they ask first and give toys back, at least during this learning stage.)\n\nYou have some serious work to do, but it will be sooooo worth it! " } ]
240-stackexchange
[ { "from": "human", "value": "What are the differences between the Strategy design pattern and the State design pattern? please explain the difference in layman's terms?" }, { "from": "gpt", "value": "The difference simply lies in that they solve different problems: \n\n* The State pattern deals with what (state or type) an object is (in) -- it encapsulates state-dependent behavior, whereas \n* the Strategy pattern deals with how an object performs a certain task -- it encapsulates an algorithm. \n\nThe constructs for achieving these different goals are however very similar; both patterns are examples of composition with delegation.\n\nSome observations on their advantages:\n* By using the State pattern the state-holding (context) class is relieved from knowledge of what state or type it is and what states or types that are available. This means that the class adheres to the open-closed design principle (OCP): the class is closed for changes in what states/types there are, but the states/types are open to extensions.\n* By using the Strategy pattern the algorithm-using (context) class is relieved from knowledge of how to perform a certain task (-- the \"algorithm\"). This case also creates an adherence to the OCP; the class is closed for changes regarding how to perform this task, but the design is very open to additions of other algorithms for solving this task.\n\nThis likely also improves the context class' adherence to the single responsibility principle (SRP). Further the algorithm becomes easily available for reuse by other classes." } ]
241-stackexchange
[ { "from": "human", "value": "Why don't Tour de France riders always ride their TT bikes?" }, { "from": "gpt", "value": "There are 2 good reasons for this. \n\nFirst, 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 bike with more a more upright body position, a more stable weight distribution, a lighter frame, and far, far lighter wheels, is a more efficient choice for that style of ride.\n\nSecondly, a TT bike sacrifices bike handling for that extreme power and aero efficiency. The TT stages are controlled events, where there are either one rider, or one team on the course at a time, and so limitations on stability and handling are acceptable. Take the same bike in a 150 rider peloton, where riders constantly jockey for position, and where even on a stable bike losing focus for 1 second can cause a major crash, and all of a sudden, those same sacrifices in bike handling and stability are no longer a benefit for the rider or the team. They become a hazard to the team's chances of winning. And not just for the stage or the day, since a bad crash can take a rider out for the season. \n\nOr God forbid, permanently. \nFor these reasons, the UCI has seen fit to ban the bikes in non-TT events, in order to ensure rider safety. And for once, their decision makes sense." } ]
242-stackexchange
[ { "from": "human", "value": "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.)\nWho decided that 'Q' was going to be represent that sound instead of 'K', and why?" }, { "from": "gpt", "value": "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 \"Q\" is a uvular sound.\n\nEnglish doesn't distinguish between these two different sounds. But since we've got a spare letter lying around—the English letter \"Q\" is actually related to the Arabic letter ق, if you go back far enough!—it's become conventional to separate them in writing. \"Kuwait\" is spelled with a ك, so it gets a \"K\"; \"Qatar\" is spelled with a ق, so it gets a \"Q\". The \"Qur'an\", similarly, has a ق in it.\n\nNowadays, by the way, the letter \"Q\" has started to be associated with Arabic in particular, since it shows up significantly more there than in English. So in pop culture, you'll sometimes see names like \"Hakeem\" respelled to \"Haqim\"—even though the original Arabic has a ك in it! Linguistically, this is called hypercorrection, and it's the same reason you'll see words like \"forté\" with an é: English-speakers associate the acute accent with Romance loans (café, fiancé, résumé), but it has no special meaning in English, so it sometimes gets inserted where it doesn't actually belong (the original Italian word is simply forte)." } ]
243-stackexchange
[ { "from": "human", "value": "How do you add Boost libraries in CMakeLists.txt?" }, { "from": "gpt", "value": "Put this in your `CMakeLists.txt` file (change any options from OFF to ON if you want):\n\n```\nset(Boost_USE_STATIC_LIBS OFF) \nset(Boost_USE_MULTITHREADED ON) \nset(Boost_USE_STATIC_RUNTIME OFF) \nfind_package(Boost VERSION COMPONENTS *boost libraries here*) \n\nif(Boost_FOUND)\n include_directories(${Boost_INCLUDE_DIRS}) \n add_executable(progname file1.cxx file2.cxx) \n target_link_libraries(progname ${Boost_LIBRARIES})\nendif()\n```\n\nObviously you need to put the libraries you want where I put `*boost libraries here*`. For example, if you're using the `filesystem` and `regex` library you'd write:\n\n```\nfind_package(Boost VERSION COMPONENTS filesystem regex)\n```" } ]
244-stackexchange
[ { "from": "human", "value": "Quando devo fazer essa gravação direto no banco? \nQuais as situações?\nEu sei que posso gravar no banco o caminho da imagem." }, { "from": "gpt", "value": "Além do custo ser mais alto como mencionado, deve-se levar em conta vários fatores:\n\n* 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 Facebook, por exemplo, usa um sistema de arquivos personalizado para tornar o acesso mais rápido ainda e diminuir a o overhead por arquivo exigido pelos sistemas de arquivos tradicionais.\n* Clusterização: uma vantagem do banco de dados é no caso do seu sistema rodar em vários servidores, todos terão acesso uniforme aos arquivos. Porém, usar uma unidade na rede para armazenar os arquivos.\n* Disponibilidade: seu sistema vai ter muitos acessos? Isso pode sobrecarregar um banco de dados tradicional. Por outro lado, seu servidor HTTP pode usar as rotinas de acesso de baixo nível ao sistema de arquivos para enviar o stream de dados ao cliente.\n* Escalabilidade: se a demanda de volume ou disponibilidade aumentarem, será possível adicionar mais capacidade ao sistema? É muito mais fácil dividir arquivos entre servidores diferentes do que distribuir registros de uma tabela em mais servidores.\n* Flexibilidade: fazer cópias de segurança, mover arquivos de um servidor para outro, fazer algum processamento nos arquivos armazenados, tudo isso fica mais fácil se os arquivos estiverem num diretório. Se você faz o deploy em ambiente de cliente, os arquivos no disco não inviabilizam você de receber cópias do banco de dados para testes. Tente pedir para o seu cliente enviar terabytes de dados para você analisar se der algum problema no banco.\n* Overhead de leitura e gravação: o custo computacional para gravar e ler dados do banco de dados é maior do que para ler e gravar diretamente em um arquivo.\n\nExistem várias estratégias para escalar um sistema tanto em termos de disponibilidade quanto em volume. Basicamente essas estratégias consistem em distribui-los em vários vários servidores e redirecionar o usuário para cada um deles conforme algum critério. Os detalhes variam de implementação, tais como: estratégia de atualização dos dados, redundância, critérios de distribuição, etc.\nUma das grandes dificuldades em gerenciar arquivos fora do BD é que temos agora duas fontes de dados distintas e que precisam estar sempre em sincronia.\nDo ponto de vista de segurança, efetivamente há pouca diferença. Se um hacker pode comprometer um servidor, ele poderá ler tanto os arquivos gravados em disco do seu sistema quanto os arquivos do sistema de banco de dados. Se essa questão for crítica, uma alternativa é armazenar os dados criptografados.\nPorém, sempre que fiz a análise do melhor tipo de solução, o uso do sistema de arquivos sempre esteve em grande vantagem." } ]
245-stackexchange
[ { "from": "human", "value": "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" }, { "from": "gpt", "value": "Here is the regular expression you can use:\n\n```\n/^\\d*\\.?\\d*$/\n```\n\n* `^` - Beginning of the line;\n* `\\d*` - 0 or more digits;\n* `\\.?` - An optional dot (escaped, because in regex, . is a special character);\n* `\\d*` - 0 or more digits (the decimal part);\n* `$` - End of the line.\n\nThis allows for .5 decimal rather than requiring the leading zero, such as 0.5" } ]
246-stackexchange
[ { "from": "human", "value": "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 into the escape pod and didn't get caught up in the explosion. The only emergency transponder in the escape pod isn't working probably due to the destruction of the spacecraft. Given the technology of 1999, is it possible for us to sent out a distress signal to alert the leaving patrol spacecraft?\nNote: the cellphone was the most innovative product of 1999 money can buy.\nThe escape pod is not a Faraday cage we're talking about the future and the patrol spacecraft don't necessary be on a lookout for distress signal; please use these clues to your advantage.\nIf there is absolutely no way to transmit any man-made signal out, please state a valid reason why it can't be done." }, { "from": "gpt", "value": "Assets\n\n* 1 obsolete piece of short range comms kit requiring a battery you probably can't charge\n* 1 slightly malfunctioning escape pod with up to date comms that isn't working but you're still alive\n\nCurrent standards say the Mayday should be broadcast on VHF channel 16 (156.8 MHz). A 1999 phone, probably on 2g would likely use 900MHz (UHF). The slightly broken comms unit in the pod is probably using channel 16 or equivalent*. This is your first problem. The patrol ship will be listening in for signals broadcast on the mayday frequency. That's the frequency you need to hit, so first up is rebuilding your phone to that frequency.\n\nOr you could look at the pod comms system and see what's wrong.\n\nYour next problem is that your mobile phone's range is laughable in interstellar space. What's going to be even more laughable is when you try to use it in the radiation shielded environment of your escape pod. The signal, which is line of sight at the best of times, most likely won't even penetrate the hull. So now you need to hook it up to the external antenna used by the pod's own comms system.\n\nOr you could look at the pod comms system and see what's wrong.\n\nNow you need to make sure you're using the right broadcast method: are you on AM or FM? (There's no reason to think that 100 years from now they'd be able to pick up an analog signal)\n\nI'm sure you can see where I'm going with this. Fix the pod.\nUltimately all you're going to do is rebuild a copy of the pod's own comms system with a batch of obsolete components. If you're good enough to do that you're good enough to fix the pod's own system which will be much easier.\n\n*I mention channel 16 as an example to show that there are standards for distress signals and they're very different from the standards for mobiles, if you want someone to pick it up then you need to be broadcasting on a frequency they're listening on.\n\n## Distress frequencies\n\n 2182 kHz forms an essential part of the Global Maritime Distress Safety System (GMDSS). It has an associated DSC frequency at 2187.5 kHz. Other international distress frequencies, in use as of 2008, include:\n\n```121.5 MHz - civil aircraft emergency frequency\n243 MHz - military aircraft emergency frequency\n156.8 MHz - Marine VHF radio channel 16, short range maritime use\n406 MHz / 406.1 MHz - Cospas-Sarsat international satellite-based search and rescue (SAR) distress alert detection and information distribution system\n```\n\nDiscontinued frequencies\n```500 kHz Morse code is no longer monitored.\n121.5 or 243 MHz locators. (No longer automatically monitored by satellite, though still used for aircraft communication and short-range direction finding.)\nEffective 1 August 2013, the U. S. Coast Guard terminated its radio guard of the international voice distress, safety and calling frequency 2182 kHz and the international digital selective calling (DSC) distress and safety frequency 2187.5 kHz. Additionally, marine information and weather broadcasts transmitted on 2670 kHz terminated concurrently.\n```" } ]
247-stackexchange
[ { "from": "human", "value": "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?\nA quick search on the blender wiki does not lend itself to easy look-up due to all the noise in the search result.\nThis question could probably be broken down into these two main questions:\n\n* How do I point a selected camera to the current 3d-cursor location in the scene?\n* How do I point the selected camera to the currently selected object(s) in the scene?\n" }, { "from": "gpt", "value": "Situation 1: You're not looking through the camera yet\n\n* Fly Mode: Shift + F or the standard Viewport Navigation\n* Set Camera to View: Ctrl + Alt + Numpad 0\n\nSituation 2: You're already looking through the camera via Numpad 0\n\n* Select the camera: Right Mouse Button\n* Grab: G & optionally...\n\t* Lock the grab to a local axis: XX or YY or ZZ (my favorite)\n\n* Rotate:\n\t* Tilt: R\n\t* Look around: R R\n\t* Orbit around the 3D cursor: .R followed by R, or Z. (Press , afterwards)\n\n\nTips & Notes (some go beyond this question):\n\n1. In earlier versions of Blender, Fly Mode would to make the camera slowly flatten with the horizon line. It doesn't anymore, but you can reset the camera's rotation Alt + R to make the horizon flat and then use fly mode to reorient the camera while maintaining that flat horizon.\n\n2. If you decide to use another object as a target for the camera to look at, you can use the Object Constraints. To do this:\n\t* Select the camera.\n\t* Shift-select the target.\n\t* Press Ctrl T and select Track To or Damped Track To. You can modify the new constraint in the camera's Constraints panel, for example, to animate the influence." } ]
248-stackexchange
[ { "from": "human", "value": "What are the general tactics of Krav Maga as opposed to Systema? \nFor 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 and Krav Maga are both to do anything you can to defeat your attacker because they are serious about self defense. Does that mean that Krav Maga and Systema are strategical identical? Does Krav use strategies that Systema doesn't? Does Systema use any strategies that Krav doesn't? Is there a difference or do they generally work the same way?" }, { "from": "gpt", "value": "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.\n\nHowever...\nKrav Maga is basically a very raw, dangerous situation survival system (including avoidance and escape) which builds upon your natural instincts and taught in a very short space of time. Therefore it is highly stress tested. It relies on the fact that fear will set in in order to use your natural responses and turn them into functional movements to your advantage. It relies heavily on shock and awe in that defence and attack should be simultaneous where possible to capitalise on the opponent's shock value.\n\nSystema is - in many ways - the exact opposite, it is a system which teaches over a much longer period of time how to control your fear/anger/pity and teaches relaxation (through breathing/stretching) in stressful situations so that attacks on your person are less effective, better recovered from and the pressure points, levers and momentum of attackers can be manipulated to your advantage using the clarity of mind gained from your training.\n\nIn Summary\nSo in effect Krav Maga is taught fast and turns your weaknesses into strengths so your defence/attack becomes like a reflex just when you need it, while Systema is a methodology that needs to be learned and seeks to remove those weaknesses so that your defense/attacks can be more effective.\n\nAlso, another martial art, similar and somewhere between these is the Keysi Fighting Method (KFM) - developed for street fighting - but that has some actual forms that have to be learned such as the very distinctive 'Pensador' that the Christian Bale Batman uses/\n\nKFM is a lot more like Krav Maga but it makes heavy use of the 'Pensador' guard (much like the 'Rhino' Krav pose) and concentrates a much larger chunk of its time to dealing with multiple opponents and ground based fighting, as it was developed for street fighting and this is where they tend to end up. It doesn't deal with survival (avoidance and get away) as much as Krav however. There are also no weapons." } ]
249-stackexchange
[ { "from": "human", "value": "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 than because \"that's how it is\"." }, { "from": "gpt", "value": "It's a security concern. The Android documentation doesn't provide a lot of elaboration, stating simply:\n\n The procedure must be confirmed on-screen, and deletes the user data for privacy reasons.\n\nHowever, the privacy concern is relatively straightforward to extrapolate. Once the bootloader is unlocked, the device can be flashed with unsigned images. This means that it is relatively trivial to root the device, and there are actually multiple ways it can be done, such as:\n\n* Flashing a system image with root tools built in\n* Flashing a boot image that runs ```adbd``` with root by default (an \"unsecure\" image)\n* Flashing a recovery image, then using that to overwrite the system or boot partitions with ones that allow root access\n\nOnce root is obtained, all of the information on ```/data``` essentially becomes accessible. This could be emails, contact information, or many other pieces of personal information that you likely don't want in the wrong hands. \n\nTherefore, it makes sense to wipe all of this data during the unlocking procedure to ensure that there is no off-the-shelf \"official\" way of bypassing the sandboxing restrictions implemented by the Android operating system, which would thereby allow someone to steal personal data.\n\nOf course, there may be ways to root without wiping on some devices, but they rely on exploits rather than official methods like a bootloader unlock, meaning they are basically bugs." } ]
250-stackexchange
[ { "from": "human", "value": "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.\nWhat was lacking with the original PC sound chip? " }, { "from": "gpt", "value": "> The original IBM PC and later variants used an Intel 8253 or 8254 as a sound chip.\n\nThe 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.\n\nAs said before, calling a 'simple' timer a sound chip is quite a stretch. \nSince it's a digital output, no level control is available. Only on or off is possible. At best this results in rather nasty sounding square waves. There is no provision to smooth the signal (beside the inertia of the speaker membrane).\n\nAlso, the only frequencies that can be selected are those that result from dividing the base frequency (1,193,181.8 Hz) by an integer in the range of 1&ndash;65535. So even when accepting the meager signal quality, only very few notes can be played at correct frequency. Already the basic 440 Hz concert pitch will be off by .5Hz. So whatever is played using the timer will sound off pitch. Music can still sound good if a little off pitch, but only when all notes are off in the same way (*1) - which is not the case with this 'sound chip'.\n\nOf course, there are also ways to manipulate the sound even a bit better by manually handling the output - which results in 100% CPU time usage.\n\n> Why did users add sound cards such as the Adlib or Sound Blaster.\n\nSimply because they wanted sound - or at least music. Not just a beeper.\n\n> What was lacking with the original PC sound chip?\n\nAs said before, it's no sound chip at all. A sound chip will need programmable oscillators for different wave forms and at least some analogue ciruitry to make a smooth, more natural sound. Ofcourse, from an enginering point, the PC's use of a timer was a great improvement over the Apple II, its model and competition, as it allowed the beeping in parallel - not that this feature was used by BIOS or DOS.\nLast but not least, the PC is an open system. It is made to add new/better hardware. So why shoudn't there be a real sound card? Improving the machine is a core feature of the design.\n\nAddendum:\nagtoever added a comment with a great example of what was possible with the direct fiddling with the speaker. Awesome, but less than apealing when compared to even the cheapest form of soundcard, the AdLib of the same time, as used by Monkey Island. Next to zero CPU usage and crisp clear sound. Not to mention easy programming. I'd call that a huge advantage.\n\n*1 - The average human decodes frequencies relative to each other. As a result sound is still perceived as good, even if the whole scale is shifted, as long as it's in the same direction and same percentage. Output needs to be way off to be noticed by an average listener. In contrast, if notes are off by a different margin and in different directions, even less trained listeners will notice." } ]
251-stackexchange
[ { "from": "human", "value": "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 arbitrarily large.\nAn ```std::function``` should have a fixed size, but it must be able to wrap any kind of callables, including any lambdas of the same kind. How is it implemented? If ```std::function``` internally uses a pointer to its target, then what happens, when the ```std::function``` instance is copied or moved? Are there any heap allocations involved?" }, { "from": "gpt", "value": "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)>``` for the sake of simplicity):\n```struct callable_base {\n virtual int operator()(double d) = 0;\n virtual ~callable_base() {}\n};\ntemplate <typename F>\nstruct callable : callable_base {\n F functor;\n callable(F functor) : functor(functor) {}\n virtual int operator()(double d) { return functor(d); }\n};\nclass function_int_double {\n std::unique_ptr<callable_base> c;\npublic:\n template <typename F>\n function(F f) {\n c.reset(new callable<F>(f));\n }\n int operator()(double d) { return c(d); }\n// ...\n};\n```\nIn this simple approach the ```function``` object would store just a ```unique_ptr``` to a base type. For each different functor used with the ```function```, a new type derived from the base is created and an object of that type instantiated dynamically. The ```std::function``` object is always of the same size and will allocate space as needed for the different functors in the heap.\nIn real life there are different optimizations that provide performance advantages but would complicate the answer. The type could use small object optimizations, the dynamic dispatch can be replaced by a free-function pointer that takes the functor as argument to avoid one level of indirection, but the idea is basically the same.\n\nRegarding the issue of how copies of the ```std::function``` behave, a quick test indicates that copies of the internal callable object are done, rather than sharing the state.\n```// g++4.8\nint main() {\n int value = 5;\n typedef std::function<void()> fun;\n fun f1 = [=]() mutable { std::cout << value++ << '\\n' };\n fun f2 = f1;\n f1(); // prints 5\n fun f3 = f1;\n f2(); // prints 5\n f3(); // prints 6 (copy after first increment)\n}\n```\nThe test indicates that ```f2``` gets a copy of the callable entity, rather than a reference. If the callable entity was shared by the different ```std::function<>``` objects, the output of the program would have been 5, 6, 7." } ]
252-stackexchange
[ { "from": "human", "value": "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 me go \"Huh!\") After that, there were testimonies from missionaries and some music - but nothing that struck me as a sermon. \nWas I missing something, or was this an atypical service? I guess I was trying to understand what the \"pastor\"s role in the service was supposed to be - or again, is it just that Mormons are even more Baptist than baptists?\nIf someone could explain how instruction and exhortation are primarily conferred in the LDS church Id appreciate it. " }, { "from": "gpt", "value": "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 was Priesthood meeting where the brothers study the words of scripture and modern Church leaders. Those classes usually have a single instructor each week.\n\nSacrament meeting is where any equivalence of a sermon would be heard. The primary difference between Mormon services and some others is the focal event of church meetings. The purpose behind holding a sacrament meeting is to take the sacrament and renew covenants made at baptism. The actual administration of the sacrament is the most sacred public meeting to Mormons. Hearing people speak and even interpersonal communion (socializing) is only secondary, though important.\n\nMembers of a ward, or local congregation, are invited to speak by the bishop or his counselors (the basic equivalent of a pastor) and will have some time to prepare a talk. Talks should draw from the scriptures, personal experience and testimony, and focus on the Savior. Note that comments made by church members over the pulpit at a sacrament meeting do not necessarily reflect the Church's official position on a topic or even Church doctrine.\nThe talks are meant to urge, inspire, and exhort all in attendance to come to Christ, to give them an opportunity to feel the power of the Spirit, and to strengthen their faith. Often, members will come with questions in their hearts and find answers in the words that day.\n\nCounsel from leaders like a bishop sometimes occur over the pulpit, but usually this is private and individual, based on personal circumstances. The bishop and his counselors are supposed to meet with members regularly in interviews. There is no paid clergy, so all the service is volunteer.\n\nEach member is also assigned two \"home teachers\" which visit their family once a month to share a gospel message, check on well-being, and be a friend and support especially when needed. In this way, instruction is given which might also help replace a typical sermon pattern. The bishop, his counselors, and others he calls on help organize these efforts. (It has also proven to be very quick and effective during disaster response, as home teachers immediately report in on who they teach, and bishops coordinate an effort if needed.\n\nSo what you saw was apparently quite normal. Even once a month (the first Sunday), a fast and testimony meeting is held during sacrament meeting, where members forgo preparing talks and instead bear their testimonies about Christ and the gospel for the hour as they feel a desire to do so. Instruction is very member-to-member, you might say, but is guided by the direction of a bishop and other church leaders who also inspire and instruct." } ]
253-stackexchange
[ { "from": "human", "value": "A partir de un String, ```\"123-654321\"```, lo que deseo es dividirlo en dos Strings:\n```string1=123\nstring2=654321\n```" }, { "from": "gpt", "value": "Tres formas diferentes de hacerlo:\n1. Utilizando la función ```String.split()``` :\n``` String str = \"123-654321\";\n String[] parts = str.split(\"-\");\n```\nEsta solución utiliza expresiones regulares, así que no es lo más eficiente si no estas trabajando con ellas.\n\n2. Utilizando la clase ```StringTokenizer``` :\n```static private List fastSplit(final String text, final String separator, final boolean emptyStrings){\n List result = new ArrayList();\n final StringTokenizer st = new StringTokenizer(text, separator, true);\n String token = null;\n String lastToken = separator;\n while (st.hasMoreTokens()) {\n token = st.nextToken();\n if (token.equals(separator)) {\n if (lastToken.equals(separator) && emptyStrings) {\n result.add(\"\");\n }\n } else {\n result.add(token);\n }\n lastToken = token;\n }\n return result;\n}\n```\nEl problema con este método es que solo funciona bien cuando el delimitador tiene longitud 1.\n\n3. Implementarlo usando ```String.indexOf()``` :\nEn este caso si funcionará correctamente para delimitadores de cualquier longitud.\n```static private List fastSplit2(final String text, final String separator, final boolean emptyStrings) {\n final List result = new ArrayList();\n if (text != null && text.length() > 0) {\n int index1 = 0;\n int index2 = text.indexOf(separator);\n int sepLen = separator.length();\n while (index2 >= 0) {\n String token = text.substring(index1, index2);\n if (!token.isEmpty() || emptyStrings){\n result.add(token);\n }\n index1 = index2 + sepLen;\n index2 = text.indexOf(separator, index1);\n }\n if (index1 < text.length() - 1) {\n result.add(text.substring(index1));\n }\n }\n return result;\n}\n```" } ]
254-stackexchange
[ { "from": "human", "value": "What’s the difference between ```\\n``` (newline) and ```\\r``` (carriage return)?\nIn particular, are there any practical differences between ```\\n``` and ```\\r```? Are there places where one should be used instead of the other?" }, { "from": "gpt", "value": "In terms of ascii code, it's 3 -- since they're 10 and 13 respectively.\nBut seriously, there are many differences:\n\n* in Unix and all Unix-like systems, ```\\n``` is the code for end-of-line, ```\\r``` means nothing special\n* as a consequence, in C and most languages that somehow copy it (even remotely), ```\\n``` is the standard escape sequence for end of line (translated to/from OS-specific sequences as needed)\n* in old Mac systems (pre-OS X), ```\\r``` was the code for end-of-line instead\n* in Windows (and many old OSs), the code for end of line is 2 characters, ```\\r\\n```, in this order\n* as a surprising consequence (harking back to OSs much older than Windows), ```\\r\\n``` is the standard line-termination for text formats on the Internet\n* for electromechanical teletype-like \"terminals\", ```\\r``` commands the carriage to go back leftwards until it hits the leftmost stop (a slow operation), ```\\n``` commands the roller to roll up one line (a much faster operation) -- that's the reason you always have ```\\r``` before ```\\n```, so that the roller can move while the carriage is still going leftwards!-) Wikipedia has a more detailed explanation.\n* for character-mode terminals (typically emulating even-older printing ones as above), in raw mode, ```\\r``` and ```\\n``` act similarly (except both in terms of the cursor, as there is no carriage or roller.\n\nIn practice, in the modern context of writing to a text file, you should always use ```\\n``` (the underlying runtime will translate that if you're on a weird OS, e.g., Windows. The only reason to use ```\\r``` is if you're writing to a character terminal (or more likely a \"console window\" emulating it) and want the next line you write to overwrite the last one you just wrote (sometimes used for goofy \"ascii animation\" effects of e.g. progress bars) -- this is getting pretty obsolete in a world of GUIs, though" } ]
255-stackexchange
[ { "from": "human", "value": "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?" }, { "from": "gpt", "value": "There are a number of well-studied strategies; which is best in your application depends on circumstance.\n\n* Improve worst case runtime\nUsing 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(2^n)$ and might make instance sizes relevant for you tractable.\n\n* Improve expected runtime\nUsing heuristics, you can often devise algorithms that are fast on many instances. If those include most that you meet in practice, you are golden. Examples are SAT for which quite involved solvers exist, and the Simplex algorithm (which solves a polynomial problem, but still). One basic technique that is often helpful is branch and bound.\n\n* Restrict the problem\nIf you can make more assumptions on your inputs, the problem may become easy.\n\n* Structural properties\nYour inputs may have properties that simplify solving the problem, e.g. planarity, bipartiteness or missing a minor for graphs. See here for some examples of graph classes for which CLIQUE is easy. \n\n* Bounding functions of the input\nAnother thing to look at is parameterised complexity; some problems are solvable in time $O(2^kn^m)$ for $k$ some instance parameter (maximum node degree, maximum edge weight, ...) and $m$ constant. If you can bound $k$ by a polylogarithmic function in $n$ in your setting, you get polynomial algorithms. Saeed Amiri gives details in his answer.\n\n* Bounding input quantities\nFurthermore, some problems admit algorithms that run in pseudo-polynomial time, that is their runtime is bounded by a polynomial function in a number that is part of the input; the naive primality check is an example. This means that if the quantities encoded in your instances have reasonable size, you might have simple algorithms that behave well for you.\n\n* Weaken the result\nThis means that you tolerate errorneous or incomplete results. There are two main flavors:\n\n* Probabilistic algorithms\nYou only get the correct result with some probability. There are some variants, most notable Monte-Carlo and Las-Vegas algorithms. A famous example is the Miller-Rabin primality test.\n\n* Approximation algorithms\nYou no longer look for optimal solutions but almost optimal ones. Some algorithms admit relative (\"no worse than double the optimum\"), others absolute (\"no worse than $5$ plus the optimum\") bounds on the error. For many problems it is open how well they can be approximated. There are some that can be approximated arbitrarily well in polynomial time, while others are known to not allow that; check the theory of polynomial-time approximation schemes.\n\nRefer to Algorithmics for Hard Problems by Hromkovič for a thorough treatment.\n* Simplicity is beauty: Improved upper bounds for vertex cover by Chen Jianer, Iyad A. Kanj, Ge Xia (2005)\n" } ]
256-stackexchange
[ { "from": "human", "value": "Why are the lights inside commercial airplanes turned off during take off and landing?" }, { "from": "gpt", "value": "This is for safety reasons. \n\nTake-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.\n\nThe interior lights or cabin lights are adjusted to match the exterior environment, so that in case of an emergency, especially if the interior lights fail, your eyes are already accustomed to the light setting and you do not require additional valuable seconds for adjustment to a possibly darker or brighter environment. The lights are usually adjusted at dusk, night or dawn to match the exterior environment.\n\nIf the cabin lights do not fail during an emergency, the dimmed light also makes it easier to identify the \"EXIT\" signs which illuminate and make the guidance lighting on the floor easier to follow. The bright emergency lighting is more prominent to identify when the cabin light is dimmed, saving valuable seconds as the aircraft is evacuated.\n\nThis also ties in with having to raise the blinds on the windows. The blinds need to be raised during take-off and landing irrespective of the outside light situation, however, with a darker cabin, any outside light source, especially from fires or other hazards is easier to identify by the crew, making the decision process of whether one side could be inappropriate to use for evacuation faster, e.g. fire on port side --> no evacuation on that side.\n\nThe blinds are therefore raised to allow a better view for cabin crew of the outside area and external aircraft parts, such as engines, wings, etc." } ]
257-stackexchange
[ { "from": "human", "value": "The default behaviour of ```LIKE``` and the other comparison operators, ```=``` etc is case-sensitive.\nIs it possible make them case-insensitive?" }, { "from": "gpt", "value": "There are 3 main ways to perform a case-insensitive search in Oracle without using full-text indexes.\n\nUltimately 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.\n\n1. Case your column and your string identically.\nYou can force all your data to be the same case by using `UPPER()` or `LOWER()`:\n```\nselect * from my_table where upper(column_1) = upper('my_string');\n```\nor\n```\nselect * from my_table where lower(column_1) = lower('my_string');\n```\nIf `column_1` is not indexed on `upper(column_1)` or `lower(column_1)`, as appropriate, this may force a full table scan. In order to avoid this you can create a function-based index.\n```\ncreate index my_index on my_table ( lower(column_1) );\n```\nIf you're using LIKE then you have to concatenate a `%` around the string you're searching for.\n```\nselect * from my_table where lower(column_1) LIKE lower('my_string') || '%';\n```\n\n2. Use regular expressions.\nFrom Oracle 10g onwards `REGEXP_LIKE()` is available. You can specify the _match_parameter_ `'i'`, in order to perform case-insensitive searching.\n\nIn order to use this as an equality operator you must specify the start and end of the string, which is denoted by the carat and the dollar sign.\n\n```\nselect * from my_table where regexp_like(column_1, '^my_string$', 'i');\n```\nIn order to perform the equivalent of LIKE, these can be removed.\n```\nselect * from my_table where regexp_like(column_1, 'my_string', 'i');\n```\nBe careful with this as your string may contain characters that will be interpreted differently by the regular expression engine.\n\n3. Change it at the session level.\nThe NLS_SORT parameter governs the collation sequence for ordering and the various comparison operators, including `=` and LIKE. You can specify a binary, case-insensitive, sort by altering the session. This will mean that every query performed in that session will perform case-insensitive parameters.\n```\nalter session set nls_sort=BINARY_CI\n```\nThere's plenty of additional information around linguistic sorting and string searching if you want to specify a different language, or do an accent-insensitive search using BINARY_AI.\n\nYou will also need to change the NLS_COMP parameter; the default value of NLS_COMP is BINARY; but, LINGUISTIC specifies that Oracle should pay attention to the value of NLS_SORT.\n\nSo, once again, you need to alter the session\n```\nalter session set nls_comp=LINGUISTIC\n```\nYou may want to create a linguistic index to improve performance\n```\ncreate index my_linguistc_index on my_table \n (NLSSORT(column_1, 'NLS_SORT = BINARY_CI'));\n```" } ]
258-stackexchange
[ { "from": "human", "value": "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 differences, should I make the JWT authentication behave like OAuth?\nI am also using the JWT as my XSRF-TOKEN to prevent XSRF but I am being asked to keep them separate? Should I keep them separate? Any help here will be appreciated and might lead to a set of guidelines for the community." }, { "from": "gpt", "value": "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 your own system.\n\n## Detailed Answer\n\nJWT (Learn JSON Web Tokens) is just a token format. It defines a compact and self-contained mechanism for transmitting data between parties in a way that can be verified and trusted because it is digitally signed. Additionally, the encoding rules of a JWT also make these tokens very easy to use within the context of HTTP.\n\nBeing self-contained (the actual token contains information about a given subject), they are also a good choice for implementing stateless authentication mechanisms (aka Look mum, no sessions!). When going this route, the only thing a party must present to be granted access to a protected resource is the token itself, and the token in question can be called a bearer token.\n\nIn practice, what you're doing can already be classified as bearer token -based. However, do consider you're not using bearer tokens as specified by the OAuth 2.0 related specs (see RFC 6750). That would imply relying on the Authorization HTTP header and using the Bearer authentication scheme.\n\nRegarding the use of the JWT to prevent CSRF: Without knowing exact details it's difficult to ascertain the validity of that practice. To be honest, it does not seem correct and/or worthwhile. The following article (Cookies vs Tokens: The Definitive Guide) may be a useful read on this subject, particularly the XSS and XSRF Protection section.\n\nOne final piece of advice. Even if you don't need to go full OAuth 2.0, I would strongly recommend on passing your access token within the Authorization header instead of going with custom headers. If they are really bearer tokens, follow the rules of RFC 6750. If not, you can always create a custom authentication scheme and still use that header." } ]
259-stackexchange
[ { "from": "human", "value": "Gostaria de saber se existe alguma forma simples de realizar um upload de arquivos via AJAX + JSON.\nSe houver, qual seria?" }, { "from": "gpt", "value": "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.\nContudo, a formatação do envio não vai ser um JSON, mas sim no ```enctype``` que você definir no seu ```FormData```, que dependendo da linguagem que você está utilizando no backend vai ter uma forma diferente de interpretar estes dados.\n\n* application/x-www-form-urlencoded: é o enctype padrão, todos os valores de espaço são convertidos para \"+\" e caracteres não padrões são convertidos para representação ANSII HEX;\n* multipart/form-data: nenhum caractere é convertido, mantendo os valores do formulário intactos, necessário para upload de arquivos;\n* text/plain: apenas espaços são convertidos em \"+\";\n\nSendo essas as possibilidades, o que está sendo trafegado não é um JSON quando vamos comunicar enviando dados para o servidor. Esses dados são serializados para serem entregues dentro da área de data do método que você esta utilizando pra trafegar via HTTP(S) dentro dos formatos apresentados.\nDurante o upload você pode capturar (nos browsers modernos) evento de progresso do upload, conforme no exemplo abaixo.\nExemplo utilizando **jQuery**:\n\n**Formulário**\n```&lt;form id=&quot;formulario&quot; method=&quot;post&quot; enctype=&quot;multipart/form-data&quot;&gt;\n &lt;input type=&quot;text&quot; name=&quot;campo1&quot; value=&quot;hello&quot; /&gt;\n &lt;input type=&quot;text&quot; name=&quot;campo2&quot; value=&quot;world&quot; /&gt;\n &lt;input name=&quot;arquivo&quot; type=&quot;file&quot; /&gt;\n &lt;button&gt;Enviar&lt;/button&gt;\n&lt;/form&gt;\n```\n\n**Javascript**\n```$(\"#formulario\").submit(function() {\n var formData = new FormData(this);\n $.ajax({\n url: window.location.pathname,\n type: 'POST',\n data: formData,\n success: function(data) {\n alert(data)\n },\n cache: false,\n contentType: false,\n processData: false,\n xhr: function() { // Custom XMLHttpRequest\n var myXhr = $.ajaxSettings.xhr();\n if (myXhr.upload) { // Avalia se tem suporte a propriedade upload\n myXhr.upload.addEventListener('progress', function() {\n /* faz alguma coisa durante o progresso do upload */\n }, false);\n }\n return myXhr;\n }\n });\n});\n```" } ]
260-stackexchange
[ { "from": "human", "value": "Did the ancients or other pre-industrial civilisations engage in unsustainable practices?" }, { "from": "gpt", "value": "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 of life of many early societies - your herds graze the grass into oblivion, you move to another patch to return back when the grass grows back in; or you deplete the soil by overplanting, you move to another spot of land and start over, and so on.\n\nBut there's an important distinction to be made. Early societies were naturally regulated just as animal population are - by food resources. When food grows scarce, hunger strikes, and humans either start fighting for what's left, reducing population to more manageable levels, or migrate to not yet depleted lands - only cases of actual extinction are from island civilizations which cannot readily move. Meanwhile, globally environment stays balanced, and depleted spots are replenished from outside - slowly healing the damage. Modern humanity has no place to move - all land is already claimed by someone, so we have to make do with what resources we have - and consequently affects the world at global scale, which earlier cultures were incapable of.\n\nSustainability is not about return to pre-industrial way of life - it is unsustainable at modern population levels. It is about preserving the environment in human-habitable state - both by taking less from nature and by increasing effectiveness of usage of what we do need to take." } ]
261-stackexchange
[ { "from": "human", "value": "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?" }, { "from": "gpt", "value": "There are 3 distinct (fairly) well-known Josephs in the Bible, firstly in the Old Testament (mainly):\n\n* 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.\n\nHowever, it's more likely that a Joseph in the New Testament would be one of:\n\n* Joseph husband of Mary and surrogate father of Jesus (aka St. Joseph).\n* Joseph of Arimathea in whose tomb Jesus was laid to rest. \n\nThere's also another 9 or 10 more obscure Josephs referred to in the Bible*, 4 more in the Old Testament*:\n\n* Father of Igal of the tribe of Issachar (cf. Numbers 13:7).\n* One of the \"sons of Asaph\" (cf. 1 Chronicles 25:2 & 9).\n* A descendant of Binnui, a contemporary of Ezra (cf. Ezra 10:38-42).\n* Head of the priestly family of Shekaniah, a contemporary of Nehemiah (cf. Nehemiah 12:14).\n\nAnd 5 or 6 more in the New Testament:\n\n* One of the (half-)brothers of Jesus (often translated as \"Joses\" - cf. Mark 6:3).\n* The son of \"Mary\" and brother of James (possibly/probably The Mary, if so, identical to Joseph number 8. - cf. Mark 15:40 & 47).\n* The son of Mattathais (and father of Jannai) appearing in Luke's genealogy of Jesus (in which Joseph number 2. also appears - cf. Luke 3:24-25).\n* The son of Jonam (and father of Judah) also appearing in Luke's genealogy of Jesus (cf. Luke 3:30).\n* One of the nominees to replace Judas as an apostle, aka Barsabbas aka Justus (cf. Acts 1:23).\n* A Levite from Cyprus aka Barnabas who probably deserves to be listed amongst the \"well-known\" Josephs except that he is almost always referred to as Barnabas instead (cf. Acts 4:36).\n\n*That is in the Protestant Canon, there are another 3 in the Deuterocanonical books: Son of Oziel (great-grandfather of Judith - cf. Judith 8:1); Son of Zechariah (cf. 1 Maccabees 5); Brother of Judas Maccabeus (aka John - cf. 2 Maccabees 8:22)." } ]
262-stackexchange
[ { "from": "human", "value": "Para que serve o \"with\" no Python?" }, { "from": "gpt", "value": "Ele é usado para garantir finalização de recursos adquiridos.\n\nUm 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 fechamento.\nPara evitar isto usamos um ```try finally```. O ```finally``` garante a finalização. Como o código fica um pouco longo e este caso é bastante frequente a linguagem providenciou uma forma simplificada com o ```with```.\nEle consegue manipular objetos que contenham os métodos ```__enter__()``` e ```__exit__()```. Eles são chamados internamente logo no início da execução do bloco criado e dentro do ```finally``` interno criado no bloco.\nNo exemplo citado deve ficar algo parecido com isto internamente:\n```try:\n __enter__()\n open(&quot;my_file.txt&quot;) as file:\n data = file.read()\n #faça algo com &quot;data&quot;\nfinally:\n __exit__()\n```" } ]
263-stackexchange
[ { "from": "human", "value": "The question bothers me since February 2022. Why (legally) are Russian combatants in Ukraine considered soldiers (thus POWs when captured) rather than terrorists?\n\n* There is no formal declaration of war.\n* They are members an organization (Russian military) that commits acts of terrors to civilian population in clear violation of international law of war. Moreover, they either directly or indirectly contribute to the mentioned acts of terror.\n* Their state (Russia) explicitly claims that there is no war (thus unilaterally waiving the protection of law of war for Russian forces).\n\nWhy is that particular group of armed people acting in clear violation of Ukrainian law treated as &quot;soldiers in war&quot; rather than state-sponsored criminals?\nNote, that waiving the protection of law of war does not waive the protection of Ukrainian law (right to due process etc.)." }, { "from": "gpt", "value": "The third Geneva convention says in its second article (emphasis added):\n> 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.\n> The Convention shall also apply to all cases of partial or total occupation of the territory of a High Contracting Party, even if the said occupation meets with no armed resistance.\n\nThe violence in Ukraine qualifies for at least two reasons: it is an armed conflict between two high contracting parties, and it is a case of partial occupation of the territory of a high contracting party. &quot;Members of the armed forces&quot; of Russia who have &quot;fallen into the power of [Ukraine]&quot; are therefore protected by the provisions of the convention as prisoners of war as defined in the convention's fourth article.\n\nIt follows from this that the parenthetical commentary in the question's third bullet point is incorrect: refusing to call this &quot;military action&quot; a &quot;war&quot; does not in fact &quot;unilaterally waive the protection of law of war for Russian forces.&quot;\n\nAs to the allegation in the second point, even a prisoner of war who is suspected of committing a war crime is entitled to the convention's protections. Any punishment for the war crime is to be imposed by due process of law. The fact that war crimes may have been committed by other elements of Russia's armed forces is even less of a justification to deny the convention's protections to prisoners who are not individually suspected of war crimes." } ]
264-stackexchange
[ { "from": "human", "value": "What are the major branches of philosophy?" }, { "from": "gpt", "value": "The traditional branches of philosophy generally include\n* Aesthetics\n* Epistemology \n* Ethics\n* Logic\n* Metaphysics / Ontology\n\nWe can go ahead and add a few contemporary branches on to this (more examples could certainly be adduced):\n* Philosophy of Science [referring to the hard sciences] (Mathematics, Technology, etc.)\n* Philosophy of Politics [referring to the social sciences] (Society, etc.)\n* Philosophy of Religion [actually two things -- question related to the existence of God or gods AND questions relating to the sociological phenomenon of religion. Generally, referring to the former]\n* Philosophy of Value (Axiology)\n* Philosophy of Language\n* Philosophy of Mind \n\nPhilosophy of language and philosophy of mind are sometimes done in ways that mirror the philosophy of the hard sciences [e.g. cognitive science] and sometimes not.\nIn addition, we could add many schools and movements (again, more examples could certainly be added). From the 20th century alone, there is:\n* Phenomenology (Husserl)\n* Schizoanalysis (Gilles Deleuze and Felix Guattari)\n* Chaosophy (Felix Guattari)\n* Non-philosophy (Francois Laruelle)\n* Existentialism (Sartre, et al.)\n* Vienna Circle/Logical Positivism\n\nFinally, we can also consider the history of philosophy itself as constituting a series of fruitful conjunctions of cultures and eras where ideas were changing. The structure here is taken from Wikipedia's article on the History of Philosophy:\n* Western philosophy\n\t* Ancient philosophy\n\t* Medieval philosophy\n\t* Renaissance philosophy\n\t* Modern philosophy\n\t* Contemporary philosophy\n\n* Eastern philosophy\n\t* Indian philosophy\n\t* Persian philosophy\n\t* Chinese philosophy\n\t* Japanese philosophy\n\t* Buddhist philosophy\n\n* Abrahamic philosophy\n\t* Jewish philosophy\n\t* Christian philosophy\n\t* Islamic philosophy" } ]
265-stackexchange
[ { "from": "human", "value": "Are there any advantages while backpacking to hike during the night and sleep during the day?" }, { "from": "gpt", "value": "There are several reasons, though not all of them would apply for one's usual holiday trip.\n\n1. 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 their prey), has been used by humans in insecure or hostile territory for centuries and remains a standard technique for some military operations even today. \n\n2. Evading the elements: Hiking throughout the night and resting in the day can be especially useful in hot, arid conditions. For example in deserts, extreme heat during the day and severe cold in the night often come together. Hiking during the night here serves the double purpose of keeping you active and warm when it is cold while allowing you to save water resources during the day.\n\n3. Boosting morale: When conditions get worse (cold, moisture), getting up during the night and starting to hike will not only make you feel warm again, it will also boost your morale. Being active, and actively coping with a bad situation rather than staying miserable in the tent for the rest of the night will make you feel better.\n\n4. You want to avoid tourists: No, seriously, this is a real case in point. Most people travel during the day and one of the reasons we (or at least, I) get outdoors is to enjoy some quietness in the wild. Depending where you are, hiking at night is your best bet to fulfill this dream.\n\n5. Navigation (only very theoretical): Consider a situation where it is all cloudy during the day (so you do not see the sun), you lack a compass and currently have no sense of direction: if you are capable of navigating with the stars, you might consider waiting until dark and hope that the sky will clear up until then. " } ]
266-stackexchange
[ { "from": "human", "value": "I have been cautioned against blending:\n\n* Traditional fantasy elements\n\nSuch as magic systems and exotic, less plausible creatures (on a scientific level - magic tends to explain away these beasts)\n\n* Traditional sci-fi elements\n\nSuch as advanced technology and civilizations amidst the stars.\nI have taken it upon myself to harmonize the two in my current worldbuilding project. I know I cannot be the first. I love the creativity found in both, and it is going well so far. I have been exploring the potential for humanity with both tools at their disposal. (Magic and science, essentially)\nWhy do people advise to stick to one or the other?" }, { "from": "gpt", "value": " Any sufficiently advanced technology is indistinguishable from magic.\n - Arthur C Clarke\n\nThere's a reason that science fiction and fantasy are frequently shelved together - separating the two is usually a fools errand.\n\nThe Dragonriders of Pern features a preindustrial society where flying, firebreathing, teleporting, and telepathic dragons defend the skies from horrible creatures that rain down from above. They could easily be considered pure fantasy - up until the book where they discover the spacecraft that the human ancestors flew in on, and the labs where they bioengineered the dragons. \n\nIn Star Wars (arguably the most famous science fiction property of all time), the Force is really just space magic called another name. And they do all their fighting with swords. \n\nThe lists go on and on. Science fiction and fantasy are united in that they explore the impossible. Fantasy uses elements that will never be possible, while science fiction uses elements that theoretically might be possible. But the impossibility is shared. \n\n## Science fiction and fantasy are not a single genre - they are many\n\nEpic fantasy (eg Wheel of Time) and space opera (eg Star Wars) are more similar to each other than they are to urban fantasy or \"hard\" science fiction. \n\nIn some ways, it's inaccurate to call science fiction and fantasy genres at all. They're setting elements. A romance doesn't stop being a romance because it's set on a space station, and a murder mystery isn't any less mysterious because it was an elf who was murdered.\n\nThe key to mixing these elements successfully is to understand the expectations of your readers, and meeting those expectations (but in surprising ways). Genre helps define expectations.\n\nIf you're writing hard SF, readers expect to see a world that's close enough to our own that they can believe that our world could become the world of the story - magic obviously has no place here. \n\nOn the flip side, urban fantasy readers expect the author to have considered the modern world and how it might interact with the impossible. Extrapolations from science to science fiction may be natural depending on the exact nature of the setting.\n\nIf the reader has led to expect that the serial killer is a Scooby-Doo villain, then the sudden reveal that the murders were done with actual magic will violate their expectations and frustrate them (in general - there will of course be exceptions). But if the story is framed as a space cop trying to capture a vampire despite not believing that vampires are real, the readers will accept that premise as well as any other. " } ]
267-stackexchange
[ { "from": "human", "value": "Why are prions in animal diets not destroyed by the digestive system?" }, { "from": "gpt", "value": "Proteases are enzymes in your digestive system that help break down food, acting like molecular-sized scissors that cut up proteins.\n\nProteases have clefts, or subpockets, into which proteins fit, where the substrate (protein) gets cut.\n\nInfectious or pathogenic prions are resistant to proteases, because of their three-dimensional shape, which hides away parts of the prion that would normally fit in proteases and which would cause the prion to be digested.\n\nPrions that do not cause disease — normal prions — have a different three-dimensional shape that allow them to fit into proteases, and so they are not resistant to digestion:\n\nA wealth of evidence contends that the infectious pathogen causing the prion diseases, also referred to as spongiform encephalopathies, is solely comprised of PrPSc, the pathogenic isoform of the prion protein (21-23). Both PrPSc and its normal cellular counterpart, PrPC, are encoded by a cellular gene (2, 19). Physical and molecular characterization of PrPSc and PrPC has failed to reveal any chemical differences between the two isoforms (32). However, PrPSc acquires distinctive conformational characteristics upon its conversion from PrPC. Whereas PrPC is soluble in most detergents and can be easily digested by proteases, PrPScis insoluble in detergents and maintains a protease-resistant core, designated PrP27-30, which polymerizes into amyloid (25).\n\nDr. Neena Singh also discovered that prions &quot;piggyback&quot; or attach to another protein called ferritin, as they make their way through the digestive system:\n\nDisease-causing prions are thought to have passed into people when they ate beef from infected cattle, triggering the brain wasting condition called new-variant Creutzfeldt-Jakob disease, or vCJD. But researchers have not been sure exactly how prions enter the body.\nTo find out, Neena Singh and her team at Case Western Reserve University in Cleveland, Ohio, mimicked the process of eating and digesting infected meat.\nThey mashed up brain tissue that contained prions from patients who had a form of Creutzfeldt-Jakob disease. They then exposed it to a range of harsh digestive enzymes from the mouth, stomach and intestine, which normally break proteins into pieces.\nPrions, which are known to be enormously tough, escape this attack almost unscathed, they showed, as does a second type of protein called ferritin, which stores iron and is abundant in meat. The two proteins seem to stick together, they report in the Journal of Neuroscience.\nThe researchers next added the digested slurry to a lab model of the human gut: a growing sheet of cells from the intestinal lining. By attaching fluorescent tags to the two proteins, they showed that they are transported through the cells hand-in-hand. &quot;Prions probably ride piggyback&quot; through the gut wall into the body, Singh says.\n\nAttaching to ferritin may provide additional protection from digestion, insofar as this removes prions from the digestive system, where proteases are concentrated." } ]
268-stackexchange
[ { "from": "human", "value": "How slicing in Python works? Please include references where appropriate." }, { "from": "gpt", "value": "The syntax is:\n\n```\na[start:stop] # items start through stop-1\na[start:] # items start through the rest of the array\na[:stop] # items from the beginning through stop-1\na[:] # a copy of the whole array\n```\n\nThere is also the `step` value, which can be used with any of the above:\n```\na[start:stop:step] # start through not past stop, by step\n```\nThe key point to remember is that the `:stop` value represents the first value that is not in the selected slice. So, the difference between `stop` and `start` is the number of elements selected (if `step` is 1, the default).\n\nThe other feature is that `start` or `stop` may be a negative number, which means it counts from the end of the array instead of the beginning. So:\n```\na[-1] # last item in the array\na[-2:] # last two items in the array\na[:-2] # everything except the last two items\n```\nSimilarly, `step` may be a negative number:\n```\na[::-1] # all items in the array, reversed\na[1::-1] # the first two items, reversed\na[:-3:-1] # the last two items, reversed\na[-3::-1] # everything except the last two items, reversed\n```\n\nPython is kind to the programmer if there are fewer items than you ask for. For example, if you ask for ```a[:-2]``` and ```a``` only contains one element, you get an empty list instead of an error. Sometimes you would prefer the error, so you have to be aware that this may happen.\n\n## Relationship with the ```slice``` object\n\nA slice object can represent a slicing operation, i.e.:\n```\na[start:stop:step]\n```\nis equivalent to:\n```\na[slice(start, stop, step)]\n```\n\nSlice objects also behave slightly differently depending on the number of arguments, similarly to ```range()```, i.e. both ```slice(stop)``` and ```slice(start, stop[, step])``` are supported. To skip specifying a given argument, one might use ```None```, so that e.g. ```a[start:]``` is equivalent to ```a[slice(start, None)]``` or ```a[::-1]``` is equivalent to ```a[slice(None, None, -1)]```.\n\nWhile the ```:```-based notation is very helpful for simple slicing, the explicit use of ```slice()``` objects simplifies the programmatic generation of slicing." } ]
269-stackexchange
[ { "from": "human", "value": "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. \nTo be clear, the devolution I am thinking of is like taking a human being then devolving him/her to the primate stage, so lets say about as far back as Orrorin tugenensis or Paranthropus where they are in the midst of evolving from primates to Homo erectus. Please note I used human beings as an example to give context but the species undergoing devolution may not necessarily be human.\nBased on the answers, \"devolution\" does not exist so had the word in quotes to reflect this. " }, { "from": "gpt", "value": "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 nutrients by not growing a sight organ that would be useless in their environment. It isn't devolution, it's still evolution since they are changing to better suit their environment. So, at least as far as natural processes go, a species would need to become stuck in an environment for a few hundred thousand years that heavily discourages intellect, sociability, communication skills, culture, and inventiveness. That's a tough one to come up with since such traits are usually the most powerful ones for surviving something.\n\nSo here's the environment and scenario I'm thinking of. Your smart guy race is in the stone age, its pretty much on par with homo sapiens and where they were at about 10,000-15,000 years ago. But something catastrophic doesn't happen. The world slowly becomes a perfect Eden with very few predators, a perfect climate, and vast endless fields of grain and forests of fruit bearing trees. No ice age, no super-predators like we saw in said ice age. No famines or depredation, no rabid competition between several human subspecies for the same resources. The planet (Henceforth known as paradise) is literally perfect. Too perfect. Why would a species that has as close as possible to absolutely nothing to worry about need to even develop the ability to worry? Those big craniums and complex brains waste space and make childbirth more dangerous than necessary. There is absolutely nothing gained by possessing speech, abstract thought, or cooperative culture when all a species needs to do to be successful is to wander around placidly in small familial groups grazing mindlessly on the limitless amounts of food. Shelter is utterly not necessary since you have a perfect climate, nor is clothing, and food is so ludicrously plentiful there is no need to make tools. Within another 100,000 years your species that was formerly well on their way to developing things like agriculture, warfare, and tribal societies has reverted back to dumb grazers that simply live to eat and reproduce." } ]
270-stackexchange
[ { "from": "human", "value": "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.\n* 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." }, { "from": "gpt", "value": "GEDCOM is the defacto standard for exchanging genealogical data. There are some problems with GEDCOM.\n\n* 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 4 below.\n* There is enough ambiguity in the definition of GEDCOM that different vendors have interpreted a few parts of the format inconsistently. Though they support the same tags, they can't consistently share data that uses those tags.\n* Some systems don't implement all parts of the GEDCOM format. So, when they import GEDCOM data that includes those parts, they lose that information.\n* GEDCOM has facilities that allow different vendors to extend it by adding new tags that allow them to add new types of data to GEDCOM. Others systems that do not use the same set of extensions looe that information on import.\n\nThere have been a few attempts to create new standards and formats for exchanging genealogical data. An older one that is often mentioned is the GenTech model. Recently there have been two efforts underway, Better GEDCOM and GEDCOM-X. Better GEDCOM is now inactive. However, the currently developing FHISO effort evolved from it. GEDCOM-X is an effort of Family Search (an organ of the LDS) and is currently a work in progress.\nA number of individuals have also offered up new formats for archiving and tranferring genealogical data. None of these have generated enough traction to attract critical mass of interest." } ]
271-stackexchange
[ { "from": "human", "value": "Is it ever possible that ```(a== 1 && a ==2 && a==3)``` could evaluate to true in JavaScript?" }, { "from": "gpt", "value": "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.\n```\nconst a = {\n i: 1,\n toString: function () {\n return a.i++;\n }\n}\n\nif(a == 1 && a == 2 && a == 3) {\n console.log('Hello World!');\n}\n```\n\nThe reason this works is due to the use of the loose equality operator. When using loose equality, if one of the operands is of a different type than the other, the engine will attempt to convert one to the other. In the case of an object on the left and a number on the right, it will attempt to convert the object to a number by first calling ```valueOf``` if it is callable, and failing that, it will call ```toString```. I used ```toString``` in this case simply because it's what came to mind, ```valueOf``` would make more sense. If I instead returned a string from ```toString```, the engine would have then attempted to convert the string to a number giving us the same end result, though with a slightly longer path." } ]
272-stackexchange
[ { "from": "human", "value": "Gostaria de saber qual é a real diferença entre o ```String``` (s maiúsculo) e o ```string``` (s minúsculo).\nAparentemente os dois têm os mesmos objetivos, porém qual é \"melhor\" para ser utilizado?" }, { "from": "gpt", "value": "Já foi dito que ```string``` é apenas um alias para o tipo ```String```.\nPara 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 comporta um alias.\nDiferenças úteis na utilização e escolha:\n\n* ```string``` é apenas uma forma mais simples de usar o tipo ```String``` no C#, ou seja, ```string``` é a forma de &quot;tipar&quot; uma cadeia de caracteres no C# e ```String``` é um tipo do CLR. No C#, dependendo do contexto, é melhor usar uma ou outra forma. O tipo ```String``` presente no namespace ```System``` pode ser usado em qualquer linguagem que se utilize do CLR.\n\n* ```string``` não pode ser usado com reflexão. ```String``` deve ser usado no lugar.\n\n* ```String``` pode ser usado para criar outros aliases:\n``` using str = System.String;\n //...\n str s = &quot;Foi usado outro alias para string.&quot;;\n // a variável 's' é do tipo System.String que é o mesmo que ser string\n```\nMas esse é apenas um exemplo, não há necessidade e não é recomendado usar em código real. Existe sim casos que um alias pode ser útil, mas esse apenas dificulta a leitura para quem não está acostumado com isso, sem trazer nenhum benefício.\n\n* Há alguns locais que ocorre o oposto e criar um alias pode trazer mais legibilidade ao código.\n\n* Em outros casos pode ser apenas estranho usar um ou outro e dificultar a leitura.\n\n* Na verdade o tipo ```String``` deve ser usado como ```System.String``` ou onde exista um ```using System```, enquanto que ```string``` pode ser usado em qualquer código que o compilador já entenderá.\n\n* ```String``` pode ser usado como identificador válido. ```string``` é uma palavra reservada e não pode ser um identificador.\n\n* Há uma diferença na forma como o syntax highlight apresenta ambos. Pois uma forma é tipo e a outra é palavra chave.\n\n* Apesar da recomendação geral em usar ```string``` sempre que possível enquanto está programando em C#, há controvérsias no seu uso. Alguns alegam que ```String``` é preferencial para deixar claro, através do Pascal Case, que você está usando um tipo de referência(en).\nMas não faz muito sentido porque ```Int32``` é tipo de valor(en) e também usa PascalCase (ou lowerCamelCase). E ainda ele, apesar de ser tipo de referência, tem semântica de valor. Então mesmo que usasse a lógica de Pascal Case para tipo de referência, e Camel Case (ou (UpperCamelCase) para tipo de valor, pela semântica, que é o que importa, ele deveria ser Camel Case, ou seja, deveria começar com minúsculo mesmo.\nNo CLR o estilo de case é usado para ajudar determinar outras características do identificador.\n\n* É possível substituir o tipo oficial por outro seu com mesmo nome se fizer tudo corretamente. O *alias *apontará para esse novo tipo que tem o mesmo nome e é colocado da mesma forma. Se ele não for exatamente o mesmo nome (incluindo o namespace) aí ele só pode ser usado opcionalmente o que quase inviabiliza o uso real.\n\n\nImportante lembrar que ele é um tipo como outro qualquer por referência com semântica por valor e algumas facilidades que o compilador dá. O mesmo vale se usar ```String```.\nTambém vale lembrar que não existe tipo primitivo em C# (outra referência). Isso existe só como conceito do CLR, mesmo assim não como algo fundamental.\nImportante notar que tudo isso é válido para o C#, outras linguagens como Java, ou até mesmo VB.NET podem ter mais diferenças.\n\n* Documentação oficial do ```string``` dizendo que é um alias.\n* FAQ reafirmando sobre aliases de tipos.\n* ```System.String```.\n\nColoquei no GitHub para referência futura." } ]
273-stackexchange
[ { "from": "human", "value": "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?" }, { "from": "gpt", "value": "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 you will never do as good a job reviewing your own stuff as someone else, there are some things you can do to help however\n\n* Check tests exist and pass (possibly have a target test coverage, though you may need to break this in certain cases, but you should be able to justify why)\n* Check Static analysis passes (there will also be false negatives here but that is fine as long as you can justify why then its fine to suppress them)\n* Maintain a check list of further things to check in review (ideally add this as new static analysis rules if possible) make sure you check anything the SA can't check, e.g., are comments still valid, are things named appropriately (naming things is of course, one of the 2 hard problems known to computer science)\n* If a fault is identified check if the cause is systemic and look at why it wasn't found in earlier tests or reviews\n\nThis of course is useful when you are reviewing others code as well" } ]
274-stackexchange
[ { "from": "human", "value": "Assume an environment with a puppet-managed cluster of different servers - various hardware, software, operating systems, virtual/dedicated, etc.\nWould you choose meaningful hostnames (mysqlmaster01..99, mysqlslave001..999, vpnprimary, vpnbackup, etc.) or would you prefer meaningless hostnames such as characters from a book or movie?\nThe problem I see with meaningful hostnames is that names usually represent a single service and if a server has more than one purpose it gets really messy (especially if server roles change often).\nIsn't mapping a service name to an IP address and maintaining that mapping what DNS is supposed to do?\nWhat are the advantages and drawbacks of both approaches and what actual problems have you had to tackle with the approach you chose?" }, { "from": "gpt", "value": "This largely comes down to whether your servers are ```pets``` or ```livestock```.\n\nPets 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.\n\nLivestock get numbers. They're mostly identical, and what differences there are, we don't care about and usually try to minimize. When one gets sick, we put it down and get another one. Fully virtualized servers, especially IaaS servers such as AWS, are livestock.\n\nIn most complex environments, you have a mix. Your web backends, for instance, are almost certainly livestock. If you need more, you spin up a few more with the standard config; if you don't need as many you turn some off. Your database servers, in some configurations, are pets. There may be a lot of special setup on each; you may even be running them on bare metal instead of virtualization.\n\nOf course, in either environment, you can name SERVICES and address those directly. This is a best practice in any case; your developers shouldn't need to know or care what the actual hostname of a service is. The hostname should be a purely operational detail. Think, then, of encoding information that is useful to your ops staff in the hostnames - for instance, it's often helpful to denote which datacenter a server is in." } ]
275-stackexchange
[ { "from": "human", "value": "Best way to start investing, for a young person just starting their career?" }, { "from": "gpt", "value": "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. \n\nNow, with that out of the way, there's really two kinds of \"investing\" to think about:\n\n1. Retirement (401k, IRA, SIMPLE, etc)\n2. Non-Retirement (Brokerage account, investing in individual stocks, day trading, etc)\n\nFor most individuals, it is best to take care of #1 first. Most people shouldn't even think about #2 until they have fully funded their retirement accounts, established an emergency fund, and gotten their debt under control.\n\nThere are lots of financial incentives for retirement investing, both from your employer, and the government. All the more reason to take care of #1 before #2!\n\nYour employer probably offers some kind of 401k (or equivalent, like a 403b) with a company-provided match. This is a potential 100% return on your investment after the vesting period. No investment you make on your own will ever match that. Additionally, there are tax advantages to contributing to the 401k. (The money you contribute doesn't count as taxable income.)\n\n***The best way to start investing is to learn about your employer's retirement plan, and contribute enough to fully utilize the employer matching.***\n\nBeyond this, there are also Individual Retirement Accounts (IRAs) you can open to contribute money to on your own. You should open one of these and start contributing, but only after you have fully utilized the employer matching with the 401k. The IRA won't give you that 100% ROI that the 401k will.\n\nKeep in mind that retirement investments are pretty much \"walled off\" from your day-to-day financial life. Money that goes into a retirement account generally can't be touched until retirement age, unless you want to pay lots of taxes and penalties. You generally don't want to put the money for your house down payment into a retirement account.\n\nOne other thing to note: Your 401K and your IRA is an account that you put money into. Just because the money is sitting in the account doesn't necessarily mean it is invested. You put the money into this account, and then you use this money for investments. How you invest the retirement money is a topic unto itself. Here is a good starting point." } ]
276-stackexchange
[ { "from": "human", "value": "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.\nWhat is quantum gate teleportation and what is it used for?\nI am particularly interested in possible applications in simulating quantum circuits." }, { "from": "gpt", "value": "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.\n\nUsually, teleportation works by having an unknown quantum state $|\\psi\\rangle$ held by Alice, and two qubits in the Bell state $|\\Psi\\rangle=(|00\\rangle+|11\\rangle)/\\sqrt{2}$ shared between Alice and Bob. Alice performs a Bell state measurement, getting one of 4 possible answers and Bob holds on his qubit, depending on the measurement result of Alice, one of the 4 states $|\\psi\\rangle,X|\\psi\\rangle,Z|\\psi\\rangle,ZX|\\psi\\rangle.$ So, once Bob learns what result Alice got, he can compensate by applying the appropriate Paulis.\n\nLet $U$ be a 1-qubit unitary. Assume Alice and Bob share $(\\mathbb{I}\\otimes U)|\\Psi\\rangle$ instead of $|\\Psi\\rangle$. If they repeat the teleportation protocol, Bob now has one of $U|\\psi\\rangle,UX|\\psi\\rangle,UZ|\\psi\\rangle,UZX|\\psi\\rangle$, which we can rewrite as $U|\\psi\\rangle,(UXU^\\dagger)U|\\psi\\rangle,(UZU^\\dagger)U|\\psi\\rangle,(UZXU^\\dagger)U|\\psi\\rangle.$ The compensations that Bob has to make for a given measurement result are given by the bracketed terms. Often, these are no worse than the compensations you would have to make for normal teleportation (i.e. just the Pauli rotations). For example, if $U$ is the Hadamard rotation, then the corrections are just $(\\mathbb{I},Z,X,XZ)$ respectively. So, you can apply the Hadamard during teleportation just be changing the state that you teleport through (There is a strong connection here to the Choi-Jamiołkowski isomorphism). You can do the same for Pauli gates, and the phase gate $\\sqrt{Z}=S$. Moreover, if you repeat this protocol to build up a more complicated computation, it is often sufficient to keep a record of what these corrections are, and to apply them later.\n\nEven if you don't only need the Pauli gates (as is the case for $T=\\sqrt{S}$), the compensations may be easier than implementing the gate directly. This is the basis of the construction of the fault-tolerant T gate.\n\nIn fact, you can do something similar to apply a controlled-NOT between a pair of qubits as well. This time, the state you need is $|\\Psi\\rangle_{A_1B_1}|\\Psi\\rangle_{A_1B_1}$, and a controlled-NOT applied between $B_1$ and $B_2$. This time, there are 16 possible compensating rotations, but all of them are just about how Pauli operations propagate through the action of a controlled-NOT and, again, that just gives Pauli operations out." } ]
277-stackexchange
[ { "from": "human", "value": "What does it mean for an album to be remastered?" }, { "from": "gpt", "value": "Mastering is a separate art from recording or mixing. According to the Wikipedia article, the principle processes of mastering are:\n\n* Editing minor flaws.\n* Applying noise reduction to eliminate clicks, dropouts, hum and hiss.\n* Adjusting stereo width.\n* Adding ambience.\n* Equalize audio across tracks for the purpose of optimized frequency distribution.\n* Adjust volume.\n* Dynamic range compression or expansion.\n* Peak limit.\n* Dither.\n\nThe common thread between these processes is that they can be performed on the complete mixed recording, not just on individual tracks of a recording. Because of this, mastering can be performed at any time on any audio source.\nAs for the reason why so many works are remastered, the most likely reason is to keep up with new home theater audio formats. If you have a massive 7.2 surround system, it would be a shame if there wasn't a professionally mastered 7.2 format of \"Dark Side of the Moon\" to utilize that power. Every time new audio encoding formats become widespread (48kHz at 16bits, 92kHz at 24bits, etc.), your favorite audio source will need to be remastered to sound good in that format." } ]
278-stackexchange
[ { "from": "human", "value": "What's the best way to iterate over the items in a ```HashMap```?" }, { "from": "gpt", "value": "Extracted from the reference How to Iterate Over a Map in Java:\nThere 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 implementation (```HashMap```, ```TreeMap```, ```LinkedHashMap```, ```Hashtable```, etc.)\n\nMethod #1: Iterating over entries using a For-Each loop.\nThis is the most common method and is preferable in most cases. It should be used if you need both map keys and values in the loop.\n```Map map = new HashMap();\nfor (Map.Entry entry : map.entrySet()) {\n System.out.println(\"Key = \" + entry.getKey() + \", Value = \" + entry.getValue());\n}\n```\nNote that the For-Each loop was introduced in Java 5, so this method is working only in newer versions of the language. Also a For-Each loop will throw ```NullPointerException``` if you try to iterate over a map that is null, so before iterating you should always check for null references.\n\nMethod #2: Iterating over keys or values using a For-Each loop.\nIf you need only keys or values from the map, you can iterate over keySet or values instead of entrySet.\n```Map map = new HashMap();\n// Iterating over keys only\nfor (Integer key : map.keySet()) {\n System.out.println(\"Key = \" + key);\n}\n// Iterating over values only\nfor (Integer value : map.values()) {\n System.out.println(\"Value = \" + value);\n}\n```\nThis method gives a slight performance advantage over ```entrySet``` iteration (about 10% faster) and is more clean.\n\nMethod #3: Iterating using Iterator.\nUsing Generics:\n```Map map = new HashMap();\nIterator> entries = map.entrySet().iterator();\nwhile (entries.hasNext()) {\n Map.Entry entry = entries.next();\n System.out.println(\"Key = \" + entry.getKey() + \", Value = \" + entry.getValue());\n}\n```\nWithout Generics:\n```Map map = new HashMap();\nIterator entries = map.entrySet().iterator();\nwhile (entries.hasNext()) {\n Map.Entry entry = (Map.Entry) entries.next();\n Integer key = (Integer)entry.getKey();\n Integer value = (Integer)entry.getValue();\n System.out.println(\"Key = \" + key + \", Value = \" + value);\n}\n```\nYou can also use same technique to iterate over ```keySet``` or values.\nThis method might look redundant, but it has its own advantages. First of all, it is the only way to iterate over a map in older versions of Java. The other important feature is that it is the only method that allows you to remove entries from the map during iteration by calling ```iterator.remove()```. If you try to do this during For-Each iteration you will get \"unpredictable results\" according to Javadoc.\nFrom a performance point of view this method is equal to a For-Each iteration.\n\nMethod #4: Iterating over keys and searching for values (inefficient).\n```Map map = new HashMap();\nfor (Integer key : map.keySet()) {\n Integer value = map.get(key);\n System.out.println(\"Key = \" + key + \", Value = \" + value);\n}\n```\nThis might look like a cleaner alternative for method #1, but in practice it is pretty slow and inefficient as getting values by a key might be time-consuming (this method in different Map implementations is 20%-200% slower than method #1). If you have FindBugs installed, it will detect this and warn you about inefficient iteration. This method should be avoided.\n\nConclusion:\nIf you need only keys or values from the map, use method #2. If you are stuck with older version of Java (less than 5) or planning to remove entries during iteration, you have to use method #3. Otherwise use method #1." } ]
279-stackexchange
[ { "from": "human", "value": "Why did people start using CO2 (instead of e.g. oxygen) for carbonated drinks?" }, { "from": "gpt", "value": "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.\n\nSlightly 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.\n\nCarbonated water releases CO2 bubbles for many minutes after pressure is released (dissolved carbonic acid reforming), which is an important presentation effect that other gases do not generally have.\n\nIn many countries the local water supply is slightly alkaline (due to limestone rock being very common), and this can leave a bad after-taste, and make food in your mouth taste soapy. The addition of weak acids to water helps with neutralising this effect.\n\nAround the world, some lucky towns have natural springs with effervescent water (carbonated water), and man-made carbonated water is just imitating this. In history people have often travelled great distances to try effervescent water, so its popularity is well recorded.\n\nNitrogen is used for water pressurisation in brewing and cooking as it leaves little or no taste, and generally does not form other chemical compounds. It's used mainly when bubbles are required, but not an acidic taste.\n\nOxygen is unsuitable for water pressurisation as very little can be dissolved at normal soda pressures, and it has no taste, but may readily form unwanted chemical compounds.\n\nIn the 18th century, Joseph Priestley was the first person to document this manufacturing discovery. He noted precisely that it tasted good, and that it was similar to the German Selters water. He was discovering \"airs\" (gases), and uniquely identified quite a few different gases. CO2 was the only one he listed as tasting good. His cheap source of CO2 was the fermenting grains from the nearby brewery." } ]
280-stackexchange
[ { "from": "human", "value": "Say I have a file ```/templates/apple``` and I want to\n\n* put it in two different places and then\n* remove the original.\n\nSo, ```/templates/apple``` will be copied to ```/templates/used``` AND ```/templates/inuse```\nand then after that I’d like to remove the original.\nIs ```cp``` the best way to do this, followed by ```rm```? Or is there a better way?\nI want to do it all in one line so I’m thinking it would look something like:\n```cp /templates/apple /templates/used | cp /templates/apple /templates/inuse | rm /templates/apple\n```\nIs this the correct syntax?" }, { "from": "gpt", "value": "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:\n```cp /templates/apple /templates/used && cp /templates/apple /templates/inuse && rm /templates/apple\n```\nOr \n```cp /templates/apple /templates/used && mv /templates/apple /templates/inuse\n```\n\nTo summarize (non-exhaustively) bash's command operators/separators:\n\n* ```|``` pipes (pipelines) the standard output (```stdout```) of one command into the standard input of another one. Note that ```stderr``` still goes into its default destination, whatever that happen to be.\n* ```|&```pipes both ```stdout``` and ```stderr``` of one command into the standard input of another one. Very useful, available in bash version 4 and above.\n* ```&&``` executes the right-hand command of ```&&``` only if the previous one succeeded.\n* ```||``` executes the right-hand command of ```||``` only it the previous one failed.\n* ```;``` executes the right-hand command of ```;``` always regardless whether the previous command succeeded or failed. Unless ```set -e``` was previously invoked, which causes ```bash``` to fail on an error.\n" } ]
281-stackexchange
[ { "from": "human", "value": "When are Decision Diagrams the right way to model and solve a problem?" }, { "from": "gpt", "value": "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. Relaxed decision diagrams provide dual bounds on the objective function -- a larger width can produce a stronger bound.\nThe relationship between the size of the decision diagram and the underlying combinatorial structure of the problem is well studied in the computer science literature; see for example the textbook by Wegener. The most important feature that influences the size is the variable ordering. We can use this to come up with some general guidelines on when a DD may be successful for combinatorial optimization:\n\n* The problem has a sequential structure, and decisions for stage $i$ depend only on the decisions made in stages $i-k$ through $i-1$, for small $k$.\n* The induced width of the constraint graph of the problem is small.\n* For a MIP model, the constraint matrix has a small bandwidth.\n* For knapsack-like problems, the maximum `budget' is relatively small.\n\nNote that in some of the above cases, precise characterization of 'small' may yield (pseudo-)polynomial bounds on the size of the exact DD. In practice, relaxed DDs will always have polynomial size.\nThere are several areas of combinatorial optimization in which decision diagrams have been successfully applied:\n\n* Sequencing and routing problems. For example, single machine scheduling with setup times, time windows, and/or precedence constraints, which can also be applied to constrained traveling salesperson problems. A similar decision diagram representation was used by Grubhub to solve pickup-and-delivery problems.\n* Decomposition and embedding in MIP models. Decision diagrams have been used to represent subproblems in MIP models that are otherwise difficult to linearize. For example, to represent nonlinear objective functions, constrained employee schedules, or nonlinear circuit design. DDs have also been used in column generation.\n* Graph-theoretic problems. Examples include set covering, maximum independent set, and maximum cut.\n* Constraint programming. Constraint propagation based on (relaxed) decision diagrams can be much more effective than propagating domains of individual variables. This was first demonstrated on overlapping alldifferent constraints." } ]
282-stackexchange
[ { "from": "human", "value": "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 hostile intentions previously towards the protagonists of the other series.\nMy question:\nShould I avoid turning my protagonist into an antagonist? Are there any foreseeable problems with this? Will this be a problem for readers? Any tips or tricks to handle this?" }, { "from": "gpt", "value": "Sounds like a great idea!\n\nSeriously 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 for a fun ride, because it is very likely you will see your character grow in ways you didn't expect when you had them boxed in as a \"good guy\". \n\nThink about people you know in real life. If you really observe people, you come to understand that nobody is a \"good guy\". Sure there are people who are generally good and generally do good things, but nobody is perfect, and even the best people have thoughts and motivations you may not approve of. Even more interesting is the fact that two people can be absolutely opposed to one another without either one being objectively \"wrong\" or \"evil\". They might just have goals and motivations that are diametrically opposed.\n\nImagine a city council wants more tax money to build a park. A local business wants to pay less tax money so they can afford to give Christmas bonuses. The business owner isn't \"evil\", in fact, he wants to give Christmas bonuses! The city council isn't \"evil\" either, they just want a park for the kids. Sometimes goals just conflict in an irreconcilable way. That's the real world. That kind of plot provides a lot more food for thought than a two dimensional \"good versus evil\" morning cartoon romp. " } ]
283-stackexchange
[ { "from": "human", "value": "I'd never heard of anycast until a few seconds ago when I read \"What are some cool or useful server/networking tricks?\".\nThe wikipedia \"Anycast\" article on it is quite formal and doesn't really evoke a mental picture of how it would be used.\nCan someone explain in a few informal sentences what \"anycast\" is, how you configure it (just in a general sense), and what its benefits are (what does it make easier)?" }, { "from": "gpt", "value": "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.\n\nThere are several benefits to anycast. First, in steady state, users of an anycast service (DNS is an excellent example) will always connect to the 'closest' (from a routing protocol perspective) DNS server. This reduces latency, as well as providing a level of load-balancing (assuming that your consumers are evenly distributed around your network).\nAnother advantage is ease of configuration management. Rather than having to configure different DNS servers depending on where a server/workstation is deployed (Asia, America, Europe), you have one IP address that is configured in every location.\n\nDepending on how anycast is implemented, it can also provide a level of high availability. If the advertisement of the anycast route is conditional on some sort of health check (e.g. a DNS query for a well known domain, in this example), then as soon as a server fails its route can be removed. Once the network reconverges, user requests will be seamlessly forwarded to the next closest instance of DNS, without the need for any manual intervention or reconfiguration.\n\nA final advantage is that of horizontal scaling; if you find that one server is being overly loaded, simply deploy another one in a location that would allow it to take some proportion of the overloaded server's requests. Again, as no client configuration is required, this can be done very quickly." } ]
284-stackexchange
[ { "from": "human", "value": "$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$.\nYet, when I run the following code in matlab\n```A = rand(2000,2000);\nB = rand(2000,2000);\nv = rand(2000,1);\ntic\nD=zeros(size(A));\nD = A;\nfor i =1:100\n D = A + B;\n (D)*v;\nend\ntoc\ntic\nfor i =1:100\n (A*v+B*v);\nend\ntoc\n```\nThe opposite is true. Av+Bv is over twice as fast. Any explanations?" }, { "from": "gpt", "value": "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.\n$v$ and the products $Av$ and $Bv$ are all vectors of length 2000 (16K bytes in double precision), which will easily fit into a level 1 cache. The matrices $A$ and $B$ are 2000 by 2000 or about 32 megabytes in size. Your level 3 cache might be large enough to store one of these matrices if you've got a really good processor.\n\nComputing $Av$ requires reading 32 megabytes (for $A$) in from memory, reading in 16K bytes (for $v$) storing intermediate results in the L1 cache and eventually writing 16K bytes out to memory. Multiplying $Bv$ takes the same amount of work. Adding the two intermediate results to get the final result requires a trivial amount of work. That's a total of roughly 64 megabytes of reads and an insignificant number of writes.\n\nComputing $(A+B)$ requires reading 32 megabytes (for A) plus 32 megabytes (for B) from memory and writing 32 megabytes (for A+B) out. Then you have to do a single matrix-vector multiplication as above which involves reading 32 megabytes from memory (if you've got a big L3 cache, then perhaps this 32 megabytes is in that L3 cache.) That's a total of 96 megabytes of reads and 32 megabytes of writes.\n\nThus there's twice as much memory traffic involved in computing this as $(A+B)v$ instead of $Av+Bv$.\n\nNote that if you have to do many of these multiplications with different vectors $v$ but the same $A$ and $B$, then it will become more efficient to compute $A+B$ once and reuse that matrix for the matrix-vector multiplications. " } ]
285-stackexchange
[ { "from": "human", "value": "I came across a piece of code ```void *p = &&abc;```. What is the significance of ```&&``` here?\nI know about rvalue references but I think ```&&``` used in this context is different. What does ```&&``` indicate in ```void *p = &&abc;``` ?" }, { "from": "gpt", "value": "## How to find it out\n\nThat's the address of a label and it's a feature specific to GCC.\n```int main(void) {\n void* startp;\ns:\n startp = &&s;\n printf(&quot;the assignment above starts at address %p\\n&quot;, startp);\n return 0;\n}\n```\nYou could have figured it out yourself by testing:\n```int main(void) {\n void* startp;\n int a;\n startp = &&a;\n printf(&quot;startp=%p\\n&quot;, startp);\n return 0;\n}\n```\nIn which case GCC says:\n\n> error: label ‘a’ used but not defined\n\n## Under the hood - assembly\n\nYou need to know assembler to really understand this, but I'll try to explain you what an address of a label means.\nAfter the OS loads the .exe file from the disk, a component of the operating system called &quot;the loader&quot; (windows has the &quot;PE Loader&quot;, linux has &quot;ELF loader&quot; or maybe even others, if they're compiled in the kernel), it does a &quot;virtualization&quot; of that program, turning it into a process.\nThis process thinks it is the only one in RAM and it has access to the entire RAM (that is, 0x00000000-0xFFFFFFFF on a 32-bit machine).\n(the above is just a short overwiew of what's happenning, you really need to learn assembly to understand it fully, so bear with me)\nNow, the label in a source code is basically an address. &quot;goto label;&quot; does nothing else than a jump to that address (think about the instruction pointer in assembly). This label stores this RAM address, and that's how you can find out that address.\nAfter you've learned ASM, you'll realize that that address points to a instruction within the ```.text``` section of the executable. The ```.text``` section is the one which holds you program's (binary) code to be executed.\n\nYou can inspect this with:\n```\nobjdump -x a.out\n```" } ]
286-stackexchange
[ { "from": "human", "value": "When I execute \"```python```\" from the terminal with no arguments it brings up the Python interactive shell.\nWhen 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.\nHow would I do a similar detection in C or C++ or Qt?" }, { "from": "gpt", "value": "You can use ```isatty```:\n```\n#include <stdio.h>\n#include <io.h>\n... \nif (isatty(fileno(stdin)))\n printf( \"stdin is a terminal\\n\" );\nelse\n printf( \"stdin is a file or a pipe\\n\");\n```\nOn windows they're prefixed with underscores: ```_isatty```, ```_fileno```." } ]
287-stackexchange
[ { "from": "human", "value": "\"The video of Pythom Space's first rocket test has raised a few eyebrows\n\nThe video prompted hundreds of replies on Twitter, including some from rather horrified rocket scientists. &quot;We knew better as untrained college students,&quot; said Jordan Noone, the co-founder of Relativity Space.\n\nPythom “Micro jump”\nWhat exactly did they get wrong with this test?\nNote: The Pythom Space CEO did eventually respond to the original Ars Technica story linked above. It does offer their own take on some of the issues raised there and elsewhere (including some of the points in the answer below)\"" }, { "from": "gpt", "value": "The easy-to-spot stuff:\n\n* (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 other videos are emphatically not approved.\n* No personal protective gear. Nitric acid and furfurly alcohol are both toxic, and heavy loads are being lifted. Nobody is seen wearing any sort of protective gear, not even hard hats or safety glasses.\n* Insecure rigging when lifting the test object upright. A strap, particularly one being pulled at a sharp angle, is far less safe than a proper lifting point.\n* Bad angle when lifting the test object upright. This puts excess loads on things, increasing the risk of a fall or failure.\n* Using unbraced legs as a pivot point when lifting the test object upright. You can see they're on the verge of buckling.\n* (assumed) Lifting the test object while already fueled. In the event of a fall, this ensures an explosion if the tanks rupture, as the fuels are hypergolic.\n* Having people stand under a suspended load. If the test object falls, this will cause serious injury or death to at least two people.\n* Using a truck to pull the lifting cable. This provides far less control than a proper winch.\n* Having personnel in the blast area of the test object. In the event of an failure, this makes it highly likely that they will be engulfed in the fireball, struck by debris, or poisoned by fuel vapors.\n* Having personnel in the exhaust area of the test object. Even during normal operation, they will be exposed to nitric acid, furfuryl alcohol, and assorted nitrogen oxides, all of which are highly toxic.\n* Having unnecessary equipment in the test area. In the event of a failure, this can become additional flying debris.\n* Not properly securing the test object. In the event of higher-than-expected performance, this will become self-propelled debris; in the event of a premature shutdown, the resulting hop-and-crash will rupture the fuel tanks and cause an explosion.\n* Not providing a flight termination system. In the event that the test object becomes airborne, they have no way of keeping it from leaving the test area.\n* (assumed) Insufficient fire-extinguishing equipment on site. None of the area views show a pumper truck or other equipment capable of dealing with a brush fire ignited by 15+ kg of hypergolic fuels.\n* Improper fire-extinguishing equipment. At one point, you can see what appears to be an ordinary dry-chemical fire extinguisher. This should not be used when dealing with nitric acid.\n* Oxidizer-rich shutdown. You can see see the reddish cloud of nitric-acid byproducts at the end of the burn; this is likely the result of the oxidizer reacting with the engine.\n* (assumed) No post-burn decontamination of the area. The celebratory post-burn shot shows no sign of cleanup. Combined with the oxidizer-rich shutdown, this means they're likely walking through an area contaminated with nitric acid." } ]
288-stackexchange
[ { "from": "human", "value": "When should I use wp_register_script() with wp_enqueue_script() vs just wp_enqueue_script()?" }, { "from": "gpt", "value": "The ```wp_register_script()``` Codex page literally says:\n\n A safe way of registering javascripts in WordPress for later use with ```wp_enqueue_script()```.\n\nThis 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 them.\n\nFor example:\nYou have a switch statement wich loads some functionality, but two of three cases needs a particular javascript file, and one doesn't. You can enqueue the script every time, wich costs more resources, or just enqueue the script when you need it:\n```...\nwp_register_script( 'my-handy-javascript', ... );\n...\nswitch( $somevar ) {\n case 'value':\n wp_enqueue_script( 'my-handy-javascript' ); // needs the file\n ...\n break;\n case 'value2':\n wp_enqueue_script( 'my-handy-javascript' ); // needs the file\n ...\n break;\n default:\n case 'value3': // doesn't needs the file\n ...\n break;\n}\n```\nIt is not necessary to register a script and then enqueue them, but it can provide some logic in your code if you register all the scripts you need somewhere in your ```functions.php``` instead of everywhere in your code.\n\nThe Codex also tells the following:\n\n Use the ```wp_enqueue_scripts``` action to call this function, or ```admin_enqueue_scripts``` to call it on the admin side.\n\nThis means that if you want to enqueue your script on the frond-end and in the back-end, you can register a script once, and then load it on the front-end with ```wp_enqueue_script``` and in the back-end with ```admin_enqueue_script```.\nThis way you won't have the same enqueue recourse twice in one theme, plugin, widget or whatever." } ]
289-stackexchange
[ { "from": "human", "value": "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. \n\n* What are the advantages and\nlimitations of the various\napproaches?\n* Are there any guidelines available for determining which to use? \n* Is it possible to switch between the two representations in any systematic fashion?\n\nAs motivation, I would like to encode various security related logics into Coq and am wondering what the pros and cons of the different approaches are." }, { "from": "gpt", "value": "> What are the advantages and limitations of the various approaches?\n\n* Pros of deep embeddings : You can prove and define things by induction on formulas' structure. Examples of interests are the size of a formula. \n* Cons of deep embeddings: You have do deal explicitly with binding of variables. That's usually very laborious. \n\n> Are there any guidelines available for determining which to use ?\n\nShallow embeddings are very useful to import result proved in the object logic. For instance, if you have prove something in a small logic (e.g. separation logic) shallow embeddings can be a tool of choice to import your result in Coq.\nOn the other side, deep embedding are almost mandatory when you want to prove meta-theorems about the object logic (like cut-elimination for instance). \n\n> Is it possible to switch between the two representations in any systematic fashion?\n\nThe idea behind the shallow embedding is really to work directly in a model of the object formulas. Usually people will maps an object formula P directly (using notations or by doing the translation by hand) to an inhabitant of Prop. Of course, there are inhabitants of Prop which cannot be obtained by embedding a formula of the object logic. Therefore you lose some kind of completeness. \n\nSo it is possible to send every result obtained in a deep embedding setting through an interpretation function. \nHere is a little coq example: \n```\nInductive formula : Set :=\n Ftrue : formula\n | Ffalse : formula\n | Fand : formula -> formula -> formula\n | For : formula -> formula -> formula.\nFixpoint interpret (F : formula) : Prop := match F with\n Ftrue => True\n | Ffalse => False\n | Fand a b => (interpret a) /\\ (interpret b)\n | For a b => (interpret a) \\/ (interpret b)\n end.\nInductive derivable : formula -> Prop :=\n deep_axiom : derivable Ftrue\n | deep_and : forall a b, derivable a -> derivable b -> derivable (Fand a b)\n | deep_or1 : forall a b, derivable a -> derivable (For a b)\n | deep_or2 : forall a b, derivable b -> derivable (For a b).\nInductive sderivable : Prop -> Prop :=\n shallow_axiom : sderivable True\n | shallow_and : forall a b, sderivable a -> sderivable b -> sderivable (a /\\ b)\n | shallow_or1 : forall a b, sderivable a -> sderivable (a \\/ b)\n | shallow_or2 : forall a b, sderivable b -> sderivable (a \\/ b).\n(* You can prove the following lemma: *)\nLemma shallow_deep :\n forall F, derivable F -> sderivable (interpret F).\n(* You can NOT prove the following lemma :*)\nLemma t :\n forall P, sderivable P -> exists F, interpret F = P.\n```" } ]
290-stackexchange
[ { "from": "human", "value": "Prove that the union of countably many countable sets is countable." }, { "from": "gpt", "value": "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?\n\nIt may seem uncountable if you pick a naive correspondence, say $1 \\mapsto 1$, $2 \\mapsto 2 ...$, which leaves all of the negative numbers unmapped. But if we organize the integers like this:\n$$0$$\n$$1, -1$$\n$$2, -2$$\n$$3, -3$$\n$$...$$\n\nWe quickly see that there is a map that works. Map 1 to 0, 2 to 1, 3 to -1, 4 to 2, 5 to -2, etc. So given an element $x$ in $\\mathbb Z$, we either have that $1 \\mapsto x$ if $x=0$, $2x \\mapsto x$ if $x > 0$, or $2|x|+1 \\mapsto x$ if $x . So the integers are countable.\n\nWe proved this by finding a map between the integers and the natural numbers. So to show that the union of countably many sets is countable, we need to find a similar mapping. First, let's unpack \"the union of countably many countable sets is countable\":\n1. \"countable sets\" pretty simple. If $S$ is in our set of sets, there's a 1-1 correspondence between elements of $S$ and $\\mathbb N$.\n2. \"countably many countable sets\" we have a 1-1 correspondence between $\\mathbb N$ and the sets themselves. In other words, we can write the sets as $S_1$, $S_2$, $S_3$... Let's call the set of sets $\\{S_n\\}, n \\in \\mathbb N$.\n3. \"union of countably many countable sets is countable\". There is a 1-1 mapping between the elements in $\\mathbb N$ and the elements in $S_1 \\cup S_2 \\cup S_3 ...$\n\nSo how do we prove this? We need to find a correspondence, of course. Fortunately, there's a simple way to do this. Let $s_{nm}$ be the $mth$ element of $S_n$. We can do this because $S_n$ is by definition of the problem countable. We can write the elements of ALL the sets like this:\n$$s_{11}, s_{12}, s_{13} ...$$\n$$s_{21}, s_{22}, s_{23} ...$$\n$$s_{31}, s_{32}, s_{33} ...$$\n$$...$$\nNow let $1 \\mapsto s_{11}$, $2 \\mapsto s_{12}$, $3 \\mapsto s_{21}$, $4 \\mapsto s_{13}$, etc. You might notice that if we cross out every element that we've mapped, we're crossing them out in diagonal lines. With $1$ we cross out the first diagonal, $2-3$ we cross out the second diagonal, $4-6$ the third diagonal, $7-10$ the fourth diagonal, etc. The $nth$ diagonal requires us to map $n$ elements to cross it out. Since we never \"run out\" of elements in $\\mathbb N$, eventually given any diagonal we'll create a map to every element in it. Since obviously every element in $S_1 \\cup S_2 \\cup S_3 ...$ is in one of the diagonals, we've created a 1-1 map between $\\mathbb N$ and the set of sets.\n\nLet's extend this one step further. What if we made $s_{11} = 1/1$, $s_{12} = 1/2$, $s_{21} = 2/1$, etc? Then $S_1 \\cup S_2 \\cup S_3 ... = \\mathbb Q^+$! This is how you prove that the rationals are countable. Well, the positive rationals anyway. Can you extend these proofs to show that the rationals are countable?" } ]
291-stackexchange
[ { "from": "human", "value": "Você encontra na internet a afirmação que Singletons são ruins. Isto é verdade? Por quê?\nO problema seria generalizado para quaisquer objetos com instância única? Ou para qualquer coisa que tenha estado global?\nSe é tão ruim, pra que foi inventado? Ou seja, que problema ele queria resolver?\nQuais os problemas que terei se usá-lo?\nExiste alternativa viável?" }, { "from": "gpt", "value": "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.\n\n###Porque não usar\n* Acoplamento. Ao usar um Singleton você está acoplando o código a uma implementação estática e específica. Isso torna o seu código dependente dessa classe e impede, por exemplo, criar mocks em testes unitários. Desse ponto de vista a consequência é basicamente a mesma de fazer diretamente um ```new MeuObjetoImportante()```, pois é uma dependência direta da classe.\n* Escopo. O padrão Singleton aplicado conforme a definição também elimina o conceito de escopo. Isso significa que se você por alguma razão decidir que para determinados componentes da aplicação você precisa de outra implementação terá que alterar manualmente todas as classes.\n* Não garantia de uma instância única. Em certos casos o padrão pode levar à falsa segurança de que existirá apenas uma instância. Vamos supor que você projete um sistema web e quer dar acesso a um arquivo ou recurso exclusivo. Um Singleton parece uma boa prática, não é? Mas e se amanhã você fizer o deploy da aplicação em um cluster com N servidores.\n\nNo caso de Java isso também é bem complicado, pois não existe isso de uma classe por JVM. O conceito correto é uma classe por ```ClassLoader```, de forma que num mesmo servidor JEE duas aplicações diferentes podem ter, cada uma, sua própria versão de uma mesma classe. As variáveis estáticas não são compartilhadas entre essas versões da mesma classe, portanto o escopo do Singleton em Java é por ```ClassLoader``` e não por programa.\n\n###Porque usar\nEm algumas situações você sabe que vai ter só uma instância da classe. Em uma aplicação Desktop, por exemplo, não há porque ter \"frescuras\" adicionais para obter uma conexão com o banco de dados. \nTambém não vejo problemas em um objeto encapsulando alguns atributos de configuração globais. Simplesmente não valeria o esforço de implementar algum mecanismo muito elaborado para algo tão simples.\n\n###Como usar\nQuando pensamos em Singleton, logo a implementação clássica do Gang of Four nos vêm à mente. Os tópicos anteriores desta resposta consideraram isso. Porém, com a ascensão do uso de frameworks de Inversão de Controle (IoC) e Injeção de Dependência (DI), existe hoje uma forma muito mais \"segura\" e flexível de implementar o padrão: deixe o framework cuidar disso para você!\n\n###Como evitar o Singleton\nApesar de implementações mais simples poderem usar o padrão Singleton da forma \"clássica\" sem problemas, em geral seria melhor aplicar a Inversão de Controle simplesmente deixar a instância de suas dependências serem injetadas. Dessa forma, caso amanhã os requisitos mudem e você preciso injetar diferentes instâncias, ou mesmo queira criar mocks de teste, basta configurar seu container ou framework para tal, sem alterar as implementações existentes." } ]
292-stackexchange
[ { "from": "human", "value": "The construction of Solomon's temple includes a piece of furnishing described in 1 Kings 7:23 (ESV):\n\n 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.\n\nSo if the ```diameter = 10``` cubits and the ```circumference = 30``` cubits, then ```π = 3``` by the equation ```C = π * D```.\nOf course, such an object does not exist since ```π = 3.14159...``` yet clearly the sea was constructed at some point. So how do we resolve this contradiction?" }, { "from": "gpt", "value": "To start with, compare the circle the diameter we're given would make with the circle the circumference we're given would make: \nSince 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. \nNow, since the circumference attributed to our sea is only 30 cubits, it represents a smaller circle, which is 30/π or roughly 9.55 cubits in diameter. \nOr to tabulate it:\n```Circle A: ~9.55 cubits diameter, 30 cubits circumference\nCircle B: 10 cubits diameter, ~31.4 cubits circumference\n```\nGiven that, we have two diameters differing by about .45 cubits (about eight inches on an 18-inch cubit--a sizable difference). \nSince we know the sea was a physical object and not a circle bounded by an infinitesimal line, we can safely understand that the sea must be of some thickness; on this ground, it would not be unreasonable to take the shorter dimension as the inner measurement, and the longer dimension as the outer measurement, and see where that takes us.\nDividing the difference in the diameters in half, this would make the wall around our sea at least .225 cubits thick--i.e., about four inches on either end of the sea, assuming an eighteen-inch cubit. \nDo we have any authority for assuming that this is the case and saying the sea was anything like four inches thick?\nA couple of verses after this we have 1 Kings 7:26, which gives it to us outright: \n\n Its thickness was a handbreadth, and its brim was made like the brim of a cup, like the flower of a lily. It held two thousand baths.\n\nA handbreadth as a unit of measurement is generally given as between three and four inches. \n(The 'Number Pi in the Bible' site linked elsewhere gives as its rebuttal to this sort of argument the statement \"The writer makes sure that no question remains: both the diameter and the circumference are taken over-all.\" - though I'm not sure on what basis he sees that.)" } ]
293-stackexchange
[ { "from": "human", "value": "With PHP 7.2, ```each``` is deprecated. The documentation says:\n\nWarning This function has been DEPRECATED as of PHP 7.2.0. Relying on this function is highly discouraged.\n\nHow can I update my code to avoid using it? Here are some examples:\n\n* \n```$ar = $o->me;\nreset($ar);\nlist($typ, $val) = each($ar);\n```\n\n* \n```$out = array('me' => array(), 'mytype' => 2, '_php_class' => null);\n$expected = each($out);\n```\n\n* \n```for(reset($broken);$kv = each($broken);) {...}\n```\n\n* \n```list(, $this->result) = each($this->cache_data);\n```\n\n* \n```// iterating to the end of an array or a limit > the length of the array\n$i = 0;\nreset($array);\nwhile( (list($id, $item) = each($array)) || $i < 30 ) {\n // code\n $i++;\n}\n```\n\n\nWhen I execute the code on PHP 7.2 I receive the following error:\n\nDeprecated: The each() function is deprecated. This message will be suppressed on further calls" }, { "from": "gpt", "value": "\n* For your first two example cases, you could use ```key()``` and ```current()``` to assign the values you need.\n```$ar = $o->me; // reset isn't necessary, since you just created the array\n$typ = key($ar);\n$val = current($ar);\n```\n\n* \n```$out = array('me' => array(), 'mytype' => 2, '_php_class' => null);\n$expected = [key($out), current($out)];\n```\nIn those cases, you can use ```next()``` to advance the cursor afterward, but it may not be necessary if the rest of your code doesn't depend on that.\n\n* For the third case, I'd suggest just using a ```foreach()``` loop instead and assigning ```$kv``` inside the loop.\n```foreach ($broken as $k => $v) {\n $kv = [$k, $v];\n}\n```\n\n* For the fourth case, it looks like the key is disregarded in ```list()```, so you can assign the current value.\n```$this->result = current($this->cache_data);\n```\nLike the first two cases, it may be necessary to advance the cursor with ```next()``` depending on how the rest of your code interacts with ```$this->cache_data```.\n\n* Fifth can be replaced with a ```for()``` loop.\n```reset($array);\nfor ($i = 0; $i < 30; $i++) {\n $id = key($array);\n $item = current($array);\n // code\n next($array);\n}\n```\n\n" } ]
294-stackexchange
[ { "from": "human", "value": "Can someone please give an explanation of different egg preparations?" }, { "from": "gpt", "value": "Sure, here are different preparations of eggs:\n\n1. Fried Eggs:\n* Sunny Side Up -- Not flipped, unbroken yolk. The top of the egg is just barely set.\n* Basted -- Sunny Side Up, hot fat spooned over until the white surrounding the yolk is opaque.\n* Over Easy / lite -- Flipped, whites fully cooked, unbroken yolk, yolk runny.\n* Over medium -- flipped, whites fully cooked, unbroken yolk, yolk creamy (not completely runny).\n* Over Medium Well -- Flipped, unbroken yolk, yolk cooked to have a firm but wet-appearing center.\n* Over Hard -- Flipped, broken, fully-cooked yolk.\n* Over Well -- Flipped, intact, fully-cooked yolk.\n* Broken / Lightly Scrambled -- Broken in pan and gently stirred while cooking - yolk and whites should not be mixed entirely.\n* Scrambled Eggs -- Made in many different ways. Generally the eggs are mixed in a bowl before being put into the pan, and often stirred while cooking. Some recipes add fat to the eggs in the form of milk, * cream, butter, or oil. A distinction can be made between Wet/Loose or Dry, which refers to the degree of doneness.\n\n2. Omelettes:\n* Filled Omelette -- Eggs mixed before cooking, possibly with added fat as in Scrambled Eggs. Cooked in fat in a saute pan; when set but the interior still wet, previously-cooked fillings (cheese, onions, mushrooms, peppers, tomatoes...) are added, and the eggs folded over into a half-moon shape.\n* Spanish Omelette / Western Omelette -- Same as filled, but the egg mixture is poured over the fillings in a hot pan and cooked, thus incorporating the fillings into the egg.\n* Fluffy Omelette -- Whites and yolks beaten separately. Yolks are gently folded into the whites without breaking the structure of the whites. Optional toppings are added. Cooked slowly in a pan, or baked (an electric frying pan with a lid works well for this preparation).\n* French Omelette -- Cooked soft & creamy with no color on the egg. Omelette is folded 1/3 in the pan, knocked to the edge so it can be rolled out onto the plate. It ends up being folded into thirds and is very creamy and soft.\n\n3. Boiled:\nCooked in shell in water for a timed period. Some people will refer to degree of doneness by cooking time, i.e., a &quot;3-minute egg&quot; is soft-boiled with some runny white around the yolk. Some recipes call for eggs to be added to boiling water, others to be started in cold water. In the cold-water start, the pot may be left on the heat or removed when the water reaches a boil. The eggs may be shocked in ice water when removed.\n* Soft -- Yolk runny, potentially with slight unset white around the yolk.\n* Medium -- White completely set, yolk firm but with a dark, wet appearance.\n* Hard -- Yolk completely set and pale yellow.\n\n4. Poached:\nEgg cooked, out of shell, in water, stock, or other liquid -- excluding fats or oils -- at a temperature in the range of 160-180˚F (70-82˚C). There are possible degrees of doneness, however the typical poached egg has a runny but warm and thickened yolk and fully-set white.\n\n5. Coddled:\nAn egg that has been very lightly cooked (poached eggs are sometimes considered coddled). This can either be accomplished with an egg coddler or cooking an egg in its shell with water that is slightly below boiling point.\n\n6. Shirred:\nAn egg cooked in an oven at the low-mid 300's˚F (~160˚C), contained in a ramekin, until the whites are just set and the yolk is runny but thickened. Often butter or another fat is placed on top before cooking.\n\n7. Steamed:\nVery similar to shirred eggs, but the ramekin is covered with some aluminum foil and put in a steamer for 7-15 minutes.\n\n8. In a basket:\nEggs fried in a hole made in a slice of bread.\n\n9. deep fried\nMoo shu- using a strainer to drop small drops of egg into hot oil in a wok and stir. Frying in vegetables and/optionally meat or another protein then consume on mandarin pancakes with your choice of sauce." } ]
295-stackexchange
[ { "from": "human", "value": "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. \nI found a few reasons to send these clients €0,- invoices, mostly similar to the reasons to send 100% discount invoices to charity funds that I gave here:\n\n* Clarity about what has to be done and when \n* No transfers (as I would have with a 0% discount bill and returning the money as a gift)\n\nAnd also:\n\n* With an invoice I have more distinguishable clients which makes that I have more chance on getting a better certificate from the state (doesn't matter how it exactly works, this is an advantage)\n\nSuppose that these clients won't have a problem with the €0,- invoices, could there be any reason for me to not send them?\nI ask this, because I've never seen people sending invoices like this, and I can only see advantages." }, { "from": "gpt", "value": "It depends on the tax system that applies to you, but there can be consequences, and they can be very severe.\n\nGenerally economic activity is defined as oriented on profit, so giving anything for free could qualify as self-promotion or donation.\n\nIn Poland, for example, only some costs of the company spend on promotion can be considered as tax costs. So in worst case you could end with tax office refusing to acknowledge, for example, 50% of your expenses as tax costs. You would end up with fine and penalty percentages.\n\nWith donation, the danger is even greater. There was a case of baker who was giving the unsold bread to charity for free. He was told to pay the VAT from the bread that was given for free (from the price it was normally being sold - but the tax officer is free to estimate the basis price as he/she wants). With penalty percentages the sum was so big, that he has become insolvent. However, the obligation to pay VAT was only in case of wares, not services, and the law has changed recently, but in other countries the regulations may be even stricter.\n\nThere is also a potential consequence if you receive something for free. It could be interpreted as income and you would have to pay income tax from the value estimated by tax officer.\n\nAssuming, analyse your local law, consult a tax specialist and be sure you exactly want what you are doing before issuing €0 invoices." } ]
296-stackexchange
[ { "from": "human", "value": "In regards to Error handling in PHP -- As far I know there are 3 styles:\n\n* ```die()```or ```exit()``` style:\n```$con = mysql_connect(\"localhost\",\"root\",\"password\");\nif (!$con) {\n die('Could not connect: ' . mysql_error());\n}\n```\n* ```throw Exception``` style:\n``` if (!function_exists('curl_init')) {\n throw new Exception('need the CURL PHP extension.\n Recomplie PHP with curl');\n }\n```\n* ```trigger_error()``` style:\n```if(!is_array($config) && isset($config)) {\n trigger_error('Error: config is not an array or is not set', E_USER_ERROR);\n }\n```\n\nNow, in the PHP manual all three methods are used. \n\n* What I want to know is which style should I prefer & why?\n* Are these 3 drop in replacements of each other & therefore can be used interchangeably?\n\nIs it just me or everyone thinks PHP error handling options are just too many to the extent it confuses php developers?" }, { "from": "gpt", "value": "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\").\n\nYou throw Exceptions if you know that at a certain critical code point, your application can fail and you want your code to recover across multiple call-levels.\n\n```trigger_error()``` lets you fine-grain error reporting (by using different levels of error messages) and you can hide those errors from end-users (using ```set_error_handler()```) but still have them be displayed to you during testing.\n\nAlso ```trigger_error()``` can produce non-fatal messages important during development that can be suppressed in production code using a custom error handler. You can produce fatal errors, too (```E_USER_ERROR```) but those aren't recoverable. If you trigger one of those, program execution stops at that point. This is why, for fatal errors, Exceptions should be used. This way, you'll have more control over your program's flow:\n```// Example (pseudo-code for db queries):\n$db->query('START TRANSACTION');\ntry {\n while ($row = gather_data()) {\n $db->query('INSERT INTO `table` (`foo`,`bar`) VALUES(?,?)', ...);\n }\n $db->query('COMMIT');\n} catch(Exception $e) {\n $db->query('ROLLBACK');\n}\n```\nHere, if ```gather_data()``` just plain croaked (using ```E_USER_ERROR``` or ```die()```) there's a chance, previous ```INSERT``` statements would have made it into your database, even if not desired and you'd have no control over what's to happen next." } ]
297-stackexchange
[ { "from": "human", "value": "How do I change the author and committer name/email for multiple commits?" }, { "from": "gpt", "value": "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.\n```\ngit filter-branch -f --env-filter \"\n GIT_AUTHOR_NAME='Newname'\n GIT_AUTHOR_EMAIL='new@email'\n GIT_COMMITTER_NAME='Newname'\n GIT_COMMITTER_EMAIL='new@email'\n \" HEAD\n```\n\nChanging the author (or committer) would require rewriting all of the history. If you're okay with that and think it's worth it then you should check out git filter-branch. The manual page includes several examples to get you started. Also note that you can use environment variables to change the name of the author, committer, dates, etc. -- see the \"Environment Variables\" section of the git manual page.\n\nSpecifically, you can fix all the wrong author names and emails for all branches and tags with this command (source: GitHub help):\n```\n#!/bin/sh\n\ngit filter-branch --env-filter '\nOLD_EMAIL=\"[email protected]\"\nCORRECT_NAME=\"Your Correct Name\"\nCORRECT_EMAIL=\"[email protected]\"\nif [ \"$GIT_COMMITTER_EMAIL\" = \"$OLD_EMAIL\" ]\nthen\n export GIT_COMMITTER_NAME=\"$CORRECT_NAME\"\n export GIT_COMMITTER_EMAIL=\"$CORRECT_EMAIL\"\nfi\nif [ \"$GIT_AUTHOR_EMAIL\" = \"$OLD_EMAIL\" ]\nthen\n export GIT_AUTHOR_NAME=\"$CORRECT_NAME\"\n export GIT_AUTHOR_EMAIL=\"$CORRECT_EMAIL\"\nfi\n' --tag-name-filter cat -- --branches --tags\n```\nFor using alternative history filtering tool `git filter-repo`, you can first install it and construct a `git-mailmap` according to the format of `gitmailmap`.\n```\nProper Name <[email protected]> Commit Name <[email protected]>\n```\nAnd then run filter-repo with the created mailmap:\n```\ngit filter-repo --mailmap git-mailmap\n```" } ]
298-stackexchange
[ { "from": "human", "value": "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?" }, { "from": "gpt", "value": "In increasing order of complexity and price you have,\n\n* Personal Locator Beacons\n\n 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.\n\n* Satellite Messengers (Like a Garmin inReach)\n\n Much like PLBs, satellite messengers are handheld transmitting devices that are useful in backcountry areas far from reliable cell phone coverage. These user-friendly devices allow you to communicate short text messages and/or your location coordinates with friends or family back home so you can report on your trip’s status or, in an emergency, send calls for help.\n\n* Satellite Phones\n\n A satellite telephone, satellite phone, or satphone is a type of mobile phone that connects to orbiting satellites instead of terrestrial cell sites. They provide similar functionality to terrestrial mobile telephones; voice, short messaging service and low-bandwidth internet access are supported through most systems.\n\nNone of these are a substitute for good judgement and the electronics can fail or run out of batteries, but they would be the modern equivalent of a flare gun." } ]
299-stackexchange