output
stringlengths
15
17.7k
input
stringclasses
1 value
instruction
stringlengths
12
7.84k
No. There are some rules that prevent this. From the Rules of the Death Note wiki: 1. The 23-days rule How to use: XXVII * [...] * If you write, “die of disease” for the cause of death, but only write a specific time of death without the actual name of disease, the human will die from an adequate disease. But the Death Note can only operate within 23 days (in the human calendar). This is called the 23-day rule. 2. Situation/cause of death is impossible How to Use: LIV * [...] * 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. While 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. 3. Setting death after original lifespan How to Use: LVII * 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.
Suppose I wrote that I will be killed by a UFO falling from space in the year 2315 while I am lifting. Will the Note increase my lifespan? In other words, will I still be alive by then?
It depends on whose turn it is. Both abilities trigger at the same time, and so will be put on the stack together. Abilities are put on the stack in APNAP (Active Player, Non-Active Player) order.* This means that the player whose turn it is puts their ability on the stack, then the other player does. That second 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. Thus 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. * From the rules on Triggered Abilities: > 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. [...] This 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.
I have an Affa Protector enchanted with Unhallowed Pact ... My opponent kills my Affa with Dread Slaver ... Who will take control of the creature at the end? This is taking into consideration that my aura spell was cast 5 turns ago. Meaning my aura spell is NOT on the stack.
strong/weak can be thought of in relation to how the compiler, if applicable, handles typing. * Weakly typed means the compiler, if applicable, doesn't enforce correct typing. Without implicit compiler interjection, the instruction will error during run-time. ```"12345" * 1 === 12345 // string * number => number ``` Strongly typed means there is a compiler, and it wants you an explicit cast from string to integer. ```(int) "12345" * 1 === 12345 ``` In 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. Thus far, JavaScript can be categorized as Not-Strongly-Typed. That either means it's weakly-typed or un-typed. dynamic/static can be thought of in relation to how the language instructions manipulate types. * Dynamically typed means the value's type is enforced, but the variable simply represents any value of any type. ```x = 12345; // number x = "string"; // string x = { key: "value" }; // object y = 123 + x; // error or implicit conversion must take place. ``` Statically typed means the variable type is strongly enforced, and the value type is less-so enforced. ```int x = 12345; // binds x to the type int x = "string"; // too late, x is an integer - error string y = 123; // error or implicit conversion must take place. ``` Thus 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. Typed 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. ``` 2 / "blah" // produces NaN ``` Untyped 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: ``` 2 / "blah" // will be treated as 2 / 1500275048 ``` Since JavaScript behaves according to the definition of being Typed, it must be. And therefore it must be Dynamically Typed, and Weakly Typed. If anybody claims JavaScript is Untyped, it is merely for academic theory, not for practical application.
I've found that some people call JavaScript a "dynamically, weakly typed" language, but some even say "untyped"? Which is it really?
This is why you should always have spare screws on hand. Fortunately, there is a way: ## Light Method Most screws are silver. Shine a flashlight into the carpet and look for little silvery glints. This may take some time, but you'll probably find it. If your carpet is unnaturally thick... ## Magnet Method Take a 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... ## Vacuum Method Take 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... ## Organize your screws There 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. ## Stop using carpet! [Not a "find your screws" method - a tip about not frying your computer] Carpet 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.
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. My question is: what kind of method, tool or hack can I use to find small screws that falls into the floor? I 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 a theoretical perspective, a critical section is a piece of code that must not be run by multiple threads at once because the code accesses shared resources. * A mutex is an algorithm (and sometimes the name of a data structure) that is used to protect critical sections. * Semaphores and Monitors are common implementations of a mutex. In 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. Availiable synchronization primitives. * Monitor * Mutex * Semaphore * ReaderWriterLock * ReaderWriterLockSlim * Interlocked The ```lock(object)``` statement is implemented using a ```Monitor``` - see MSDN for reference. In 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.
What is the difference between mutex and critical section? Please explain from Linux, Windows perspectives? I am programming in C#, would these two terms make a difference. Please post as much as you can, with examples and such.... Thanks
```_``` has 3 main conventional uses in Python: 1. To hold the result of the last executed expression in an interactive interpreter session (see docs). This precedent was set by the standard CPython interpreter, and other interpreters have followed suit. 2. For translation lookup in i18n (see the gettext documentation for example), as in code like ```raise forms.ValidationError(_("Please enter a correct username")) ``` 3. As a general purpose "throwaway" variable name: * To indicate that part of a function result is being deliberately ignored (Conceptually, it is being discarded.), as in code like: ```label, has_label, _ = text.partition(':') ``` * 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: ```def callback(_): return True ``` This 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). Linters 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). The 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. For 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.
What is the purpose of the single underscore "_" variable in Python? What is the meaning of ```_``` after ```for``` in this code? ```if tbh.bag: n = 0 for _ in tbh.bag.atom_set(): n += 1 ```
```calloc()``` gives you a zero-initialized buffer, while ```malloc()``` leaves the memory uninitialized. For large allocations, most ```calloc``` implementations under mainstream OSes will get known-zeroed pages from the OS (e.g. via POSIX ```mmap(MAP_ANONYMOUS)``` or Windows ```VirtualAlloc```) so it doesn't need to 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. This 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. Some 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.) If 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). Embedded 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. On 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.
What is the difference between doing: ```ptr = malloc (MAXELEMS * sizeof(char *)); ``` or: ```ptr = calloc (MAXELEMS, sizeof(char*)); ``` When is it a good idea to use calloc over malloc or vice versa?
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: * 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. * 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. It is more appropriate to compare Rx with some specific libraries that are implemented based on Kotlin coroutines. Take 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. Channels 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.
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.
## Java 8 solution We can use ```lambda expression``` or ```method reference``` introduced in Java 8. In case we have some String values stored in the Priority Queue (having capacity 5) we can provide inline comparator (based on length of String) : Using lambda expression ```PriorityQueue pq= new PriorityQueue(5,(a,b) -> a.length() - b.length()); ``` Using Method reference ```PriorityQueue pq= new PriorityQueue(5, Comparator.comparing(String::length)); ``` Then we can use any of them as: ```public static void main(String[] args) { PriorityQueue pq= new PriorityQueue(5, (a,b) -> a.length() - b.length()); // or pq = new PriorityQueue(5, Comparator.comparing(String::length)); pq.add("Apple"); pq.add("PineApple"); pq.add("Custard Apple"); while (pq.size() != 0) { System.out.println(pq.remove()); } } ``` This will print: ```Apple PineApple Custard Apple ``` To reverse the order (to change it to max-priority queue) simply change the order in inline comparator or use ```reversed``` as: ```PriorityQueue pq = new PriorityQueue(5, Comparator.comparing(String::length).reversed()); ``` We can also use ```Collections.reverseOrder```: ```PriorityQueue pqInt = new PriorityQueue(10, Collections.reverseOrder()); PriorityQueue pq = new PriorityQueue(5, Collections.reverseOrder(Comparator.comparing(String::length)) ``` So we can see that ```Collections.reverseOrder``` is overloaded to take comparator which can be useful for custom objects. The ```reversed``` actually uses ```Collections.reverseOrder```: ```default Comparator reversed() { return Collections.reverseOrder(this); } ``` offer() vs add() As per the doc > 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. When 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.
How do I get a ```PriorityQueue``` to sort on what I want it to sort on? Also, is there a difference between the ```offer``` and ```add``` methods?
Follow the CamelCase Java conventions, except for VF pages and components start with a lower case letter. Triggers: * <ObjectName>Trigger - The trigger itself. One per object. * <ObjectName>TriggerHandler - Class that handles all functionality of the trigger * <ObjectName>TriggerTest Controllers: * <ClassName>Controller * <ClassName>ControllerExt * <ClassName>ControllerTest * <ClassName>ControllerExtTest Classes: * <ClassName> * <ClassName>Test (These might be Util classes or Service classes or something else). Visualforce pages and components: * <ControllerClassName>[optionalDescription] (without the suffix Controller). There might be multiple views so could also have an extra description suffix. Object Names and custom Fields * Upper_Case_With_Underscores Variables/properties/methods in Apex * camelCaseLikeJava - more easily differentiated from fields Test methods in test classes * test<methodOrFunctionalityUnderTest><ShortTestCaseDesc> - For example, testSaveOpportunityRequiredFieldsMissing, testSaveOpportunityRequiredFieldsPresent, etc. Working on something that would be used as an app or in some cases just a project? If yes, then do the following: Prefix 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. The 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.
I've looked in the Apex developer's guide and a saw the Naming Conventions section which has basically only has this: We recommend following Java standards for naming, that is, classes start with a capital letter, methods start with a lowercase verb, and variable names should be meaningful. I'm looking for something more in depth, such as end all Controllers with Controller and their tests with ControllerTest, etc. What 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.
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! The 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. Vulgar 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. Nowadays, 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!
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. This makes me wonder: Is this a common pattern in other languages? Especially ones not closely related to English.
Python have already evolve to the ```__future__``` long time ago. So how about using the amazing ```pathlib``` coming with Python 3.4 to accomplish the task instead of struggling with ```os```, ```os.path```, ```glob ```, ```shutil```, etc. So we have 3 paths here (possibly duplicated): * ```mod_path```: which is the path of the simple helper script * ```src_path```: which contains a couple of template files waiting to be copied. * ```cwd```: current directory, the destination of those template files. and the problem is: we don't have the full path of ```src_path```, only know it's relative path to the ```mod_path```. Now let's solve this with the the amazing ```pathlib```: ```# Hope you don't be imprisoned by legacy Python code :) from pathlib import Path # `cwd`: current directory is straightforward cwd = Path.cwd() # `mod_path`: According to the accepted answer and combine with future power # if we are in the `helper_script.py` mod_path = Path(__file__).parent # OR if we are `import helper_script` mod_path = Path(helper_script.__file__).parent # `src_path`: with the future power, it's just so straightforward relative_path_1 = 'same/parent/with/helper/script/' relative_path_2 = '../../or/any/level/up/' src_path_1 = (mod_path / relative_path_1).resolve() src_path_2 = (mod_path / relative_path_2).resolve() ``` In the future, it's just that simple. Moreover, we can select and check and copy/move those template files with ```pathlib```: ```if src_path != cwd: # When we have different types of files in the `src_path` for template_path in src_path.glob('*.ini'): fname = template_path.name target = cwd / fname if not target.exists(): # This is the COPY action with target.open(mode='wb') as fd: fd.write(template_path.read_bytes()) # If we want MOVE action, we could use: # template_path.replace(target) ```
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?
Setting isBodyHtml to true allows you to use HTML tags in the message body: ``` msg = new MailMessage("xxxx@gmail.com", "yyyy@gmail.com", "Message from PSSP System", "This email sent by the PSSP system<br />" + "<b>this is bold text!</b>"); msg.IsBodyHtml = true; ```
How to send HTML-formatted email in C#?
This will work, but the `i -> i` is doing some automatic unboxing which is why it "feels" strange. `mapToInt` converts the stream to an `IntStream` "of primitive int-valued elements". Either of the following will work and better explain what the compiler is doing under the hood with your original syntax: ``` integers.values().stream().mapToInt(i -> i.intValue()).sum(); integers.values().stream().mapToInt(Integer::intValue).sum(); ``` The other simple option is `BigDecimal sum = numbers.stream().reduce(BigDecimal.ZERO, BigDecimal::add);`.
I want to sum a list of Integers. It works as follows, but the syntax does not feel right. Could the code be optimized? ```Map integers; integers.values().stream().mapToInt(i -> i).sum(); ```
The ```\leavevmode``` is defined by LaTeX and plainTeX and ensures that the vertical mode is ended and horizontal mode is entered. In vertical mode, TeX stacks horizontal boxes vertically, whereas in horizontal mode, they are taken as part of the text line. For example ```\mbox{..}``` is defined as ```\leavevmode\hbox{..}``` 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. Compare: ```Text\par\hbox{Hello} World ``` Result: ``` Text Hello World ``` with: ```Text\par\mbox{Hello} World ``` Result: ``` Text Hello World ``` You 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. 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). For 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.
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?
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. If 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.
In Python specifically, how do variables get shared between threads? Although I have used ```threading.Thread``` before I never really understood or saw examples of how variables got shared. Are they shared between the main thread and the children or only among the children? When would I need to use thread local storage to avoid this sharing? I 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. Thanks in advance!
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. However, 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: 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. North 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. Known 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.
I grew up in a country where we were not allowed to leave/travel to an other country even when we were able to do so – we had the resources and dual nationality. After two decades I still can't figure out why dictators, like Kim Jong-un for example, ban people from leaving their home countries? Could it be that a dictator is usually interested in looting the country he rules, and having a smaller population means more natural resources for him and fewer protesters?
## Short answer Healthy people cannot hold their breaths until unconsciousness sets in, let alone commit suicide. ## Background According to Parkes (2005), a normal person cannot even hold their breath to unconsciousness, let alone death. Parkes says: Breath‐holding is a voluntary act, but normal subjects appear unable to breath‐hold to unconsciousness. A powerful involuntary mechanism normally overrides voluntary breath‐holding and causes the breath that defines the breakpoint. Parkes 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. The breaking point can be postponed by large lung inflations, hyperoxia and hypocapnia, and it is shortened by increased metabolic rates. Reference - Parkes, Exp Physiol (2006); 91(1): 1-15
Why can't we kill ourselves by holding our breath?
It signifies that the car is running absolutely correct. Here is the reason why: A gasoline (petrol) molecule is made up as such: C8H18 (or 8 Carbon atoms and 18 Hydrogen atoms) Energy is obtained from the combustion of it by the conversion of a hydrocarbon to carbon dioxide and water. The combustion of octane follows this reaction: 2 C8H18 + 25 O2 → 16 CO2 + 18 H2O Or 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. As 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).
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;. And 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?
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. The 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. Back 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. Today, 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.) There 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.
Why can't MX records point to an IP address?
The asterisk character, "*", in the SELECT statement is shorthand for all the columns in the table(s) involved in the query. Performance The ```*``` shorthand can be slower because: * Not all the fields are indexed, forcing a full table scan - less efficient * What you save to send ```SELECT *``` over the wire risks a full table scan * Returning more data than is needed * Returning trailing columns using variable length data type can result in search overhead Maintenance When using ```SELECT *```: * 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. * If code depends on column order, ```SELECT *``` will hide an error waiting to happen if a table had its column order changed. * Even if you need every column at the time the query is written, that might not be the case in the future * the usage complicates profiling Design ```SELECT *``` is an anti-pattern: * The purpose of the query is less obvious; the columns used by the application is opaque * It breaks the modularity rule about using strict typing whenever possible. Explicit is almost universally better. When Should "SELECT *" Be Used? It'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. Otherwise, explicitly list every column that is to be used in the query - preferably while using a table alias.
Why is ```SELECT *``` bad practice? Wouldn't it mean less code to change if you added a new column you wanted? I understand that ```SELECT COUNT(*)``` is a performance problem on some DBs, but what if you really wanted every column?
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. Very 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. Now, 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. As 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. It 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***.
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. But 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. If you fly small GA planes, do you land at the major airports in your area? What advanced preparations can you make to minimize your impact on the "big boys", and remain a good airspace citizen?
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. ``` 'Calculate the Levenshtein Distance between two strings (the number of insertions, 'deletions, and substitutions needed to transform the first string into the second) Public Function LevenshteinDistance(ByRef S1 As String, ByVal S2 As String) As Long Dim L1 As Long, L2 As Long, D() As Long 'Length of input strings and distance matrix Dim i As Long, j As Long, cost As Long 'loop counters and cost of substitution for current letter Dim cI As Long, cD As Long, cS As Long 'cost of next Insertion, Deletion and Substitution L1 = Len(S1): L2 = Len(S2) ReDim D(0 To L1, 0 To L2) For i = 0 To L1: D(i, 0) = i: Next i For j = 0 To L2: D(0, j) = j: Next j For j = 1 To L2 For i = 1 To L1 cost = Abs(StrComp(Mid$(S1, i, 1), Mid$(S2, j, 1), vbTextCompare)) cI = D(i - 1, j) + 1 cD = D(i, j - 1) + 1 cS = D(i - 1, j - 1) + cost If cI <= cD Then 'Insertion or Substitution If cI <= cS Then D(i, j) = cI Else D(i, j) = cS Else 'Deletion or Substitution If cD <= cS Then D(i, j) = cD Else D(i, j) = cS End If Next i Next j LevenshteinDistance = D(L1, L2) End Function ``` We 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. valueWords, valuePhrase, and Split function: ``` Public Function valuePhrase#(ByRef S1$, ByRef S2$) valuePhrase = LevenshteinDistance(S1, S2) End Function Public Function valueWords#(ByRef S1$, ByRef S2$) Dim wordsS1$(), wordsS2$() wordsS1 = SplitMultiDelims(S1, " _-") wordsS2 = SplitMultiDelims(S2, " _-") Dim word1%, word2%, thisD#, wordbest# Dim wordsTotal# For word1 = LBound(wordsS1) To UBound(wordsS1) wordbest = Len(S2) For word2 = LBound(wordsS2) To UBound(wordsS2) thisD = LevenshteinDistance(wordsS1(word1), wordsS2(word2)) If thisD < wordbest Then wordbest = thisD If thisD = 0 Then GoTo foundbest Next word2 foundbest: wordsTotal = wordsTotal + wordbest Next word1 valueWords = wordsTotal End Function '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ' SplitMultiDelims ' This function splits Text into an array of substrings, each substring ' delimited by any character in DelimChars. Only a single character ' may be a delimiter between two substrings, but DelimChars may ' contain any number of delimiter characters. It returns a single element ' array containing all of text if DelimChars is empty, or a 1 or greater ' element array if the Text is successfully split into substrings. ' If IgnoreConsecutiveDelimiters is true, empty array elements will not occur. ' If Limit greater than 0, the function will only split Text into 'Limit' ' array elements or less. The last element will contain the rest of Text. '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Function SplitMultiDelims(ByRef Text As String, ByRef DelimChars As String, _ Optional ByVal IgnoreConsecutiveDelimiters As Boolean = False, _ Optional ByVal Limit As Long = -1) As String() Dim ElemStart As Long, N As Long, M As Long, Elements As Long Dim lDelims As Long, lText As Long Dim Arr() As String lText = Len(Text) lDelims = Len(DelimChars) If lDelims = 0 Or lText = 0 Or Limit = 1 Then ReDim Arr(0 To 0) Arr(0) = Text SplitMultiDelims = Arr Exit Function End If ReDim Arr(0 To IIf(Limit = -1, lText - 1, Limit)) Elements = 0: ElemStart = 1 For N = 1 To lText If InStr(DelimChars, Mid(Text, N, 1)) Then Arr(Elements) = Mid(Text, ElemStart, N - ElemStart) If IgnoreConsecutiveDelimiters Then If Len(Arr(Elements)) > 0 Then Elements = Elements + 1 Else Elements = Elements + 1 End If ElemStart = N + 1 If Elements + 1 = Limit Then Exit For End If Next N 'Get the last token terminated by the end of the string into the array If ElemStart <= lText Then Arr(Elements) = Mid(Text, ElemStart) 'Since the end of string counts as the terminating delimiter, if the last character 'was also a delimiter, we treat the two as consecutive, and so ignore the last elemnent If IgnoreConsecutiveDelimiters Then If Len(Arr(Elements)) = 0 Then Elements = Elements - 1 ReDim Preserve Arr(0 To Elements) 'Chop off unused array elements SplitMultiDelims = Arr End Function ``` Using 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. To 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: ``` value = Min(phraseWeight*phraseValue, wordsWeight*wordsValue)*minWeight + Max(phraseWeight*phraseValue, wordsWeight*wordsValue)*maxWeight + lengthWeight*lengthValue ``` For 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.
I need a way to compare multiple strings to a test string and return the string that closely resembles it: ```TEST STRING: THE BROWN FOX JUMPED OVER THE RED COW CHOICE A : THE RED COW JUMPED OVER THE GREEN CHICKEN CHOICE B : THE RED COW JUMPED OVER THE RED COW CHOICE C : THE RED FOX JUMPED OVER THE BROWN COW ``` (If I did this correctly) The closest string to the "TEST STRING" should be "CHOICE C". What is the easiest way to do this? I 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!
The problem here is that you are trying to ```await``` an array of promises rather than a Promise. This doesn't do what you expect. When the object passed to ```await``` is not a Promise, ```await``` simply returns the value as-is immediately instead of trying to resolve it. So since you passed ```await``` an array (of Promise objects) here instead of a Promise, the value returned by await is simply that array, which is of type ```Promise[]```. What 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. According to the MDN docs for ```Promise.all```: The ```Promise.all(iterable)``` method returns a promise that resolves when all of the promises in the iterable argument have resolved, or rejects with the reason of the first passed promise that rejects. So in your case: ```var arr = [1, 2, 3, 4, 5]; var results: number[] = await Promise.all(arr.map(async (item): Promise => { await callAsynchronousOperation(item); return item + 1; })); ``` This will resolve the specific error you are encountering here. Depending 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.
Given the following code: ```var arr = [1,2,3,4,5]; var results: number[] = await arr.map(async (item): Promise => { await callAsynchronousOperation(item); return item + 1; }); ``` which produces the following error: TS2322: Type 'Promise[]' is not assignable to type 'number[]'. Type 'Promise is not assignable to type 'number'. How can I fix it? How can I make ```async await``` and ```Array.map``` work together?
You're talking about a device (in helicopters the tail fan imparting horizontal thrust) that counteracts the torque imparted on the main rotor (and therefore on the helicopter) by the surrounding air as the main rotor is dragged through the air. You propose instead to impart an opposite torque through a reaction wheel. 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. Now 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. You 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.
Why don't helicopters use reaction wheels to counter the main rotor?
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. The syntax would look like this: ```# Will only run on odd days: 0 0 1-31/2 * * command # Will only run on even days: 0 0 2-30/2 * * command ``` Your 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. The 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.
When configuring cron to run a command every other day using the "Day of Month" field, like so: ```1 22 */2 * * COMMAND ``` it runs every time the day of month is odd: 1,3,5,7,9 and so on. How can I configure cron to run on days of month that are even like 2,6,8,10 and so on (without specifying it literally, which is problematic as every month has a different number of days in the month)?
The TypeScript specification (8.4.3) says" Accessors for the same member name must specify the same accessibility So you have to choose a suitable alternative. Here are two options for you: You can just not have a setter, which means only the ```Test``` class is able to set the property. You can place a breakpoint on the line ```this._prop =...```. ```class Test { private _prop: string; public get prop() : string { return this._prop; } doSomething() { this._prop = 'I can set it!'; } } var test = new Test(); test._prop = 'I cannot!'; ``` Probably 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. You 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. ```class Test { private _nameBackingField: string; private get _name() : string { return this._nameBackingField; } private set _name(val: string) { this._nameBackingField = val; // other actions... notify the property has changed etc } public get name(): string { return this._name; } doSomething() { this._name += 'Additional Stuff'; } } ```
Is there a way to have a private setter for a property in TypeScript? ```class Test { private _prop: string; public get prop() : string { return this._prop; } private set prop(val: string) { //can put breakpoints here this._prop = val; } } ``` Compiler complains that 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. I though about using an interface to hide the setter, but interfaces can only define a property, not whether it has a getter on setter. Am 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. Am I missing something? If not is there a good reason for no private setters?
It's usually best to avoid dichotomies like "Is strategy X better or strategy Y better?". In most cases, strategies are not mutually exclusive but complementary. With vocabulary learning, using just one strategy is probably the least efficient. This is because every strategy has certain strengths (certain skills it 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. Using 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. It'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.
When learning vocabulary, especially with the use of SRS (Spaced Repetition System), it is interesting to use flashcards. A commonly encountered problem is how to formulate those for maximum efficiency. How does learning vocabulary through sentences, thus giving context to the used words, compare to learning to 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?
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. First, 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. Your 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. Some 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. Be 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. You 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.
Can I spend the night alone in a tent in a forest outside Stockholm in -20°C without risking my life? The backstory From the end of January, I'm starting my studies in a suburb of Stockholm. I've decided to, if it turns out plausible, not rent an apartment, but live in a tent. (This is not out of frugality, but out of a will to try something new.) I 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. However: 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? I do have camping experience, and have been hiking for three weeks, but only in summer.
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". In 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". Latimer 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.
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?
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? The 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. Why 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.
We can define cross products mathematically like if we take two vectors, we can find another vector with certain properties but why do we use it in physics, if we consider a hypothetical physical quantity like force which is equal to cross product of certain vectors? For example, the force exerted on a charge in motion in an uniform magnetic field. Why is it so? Why does that force have to be a cross product of two vectors? Is it possible to come up with them when what we do is just observe the nature?
When this happens the easiest solution is to make the virtual directory manually. First of all, you need to make sure you have the right version of ASP.Net installed and that you have installed the IIS extensions. To do this, go to the relevant .net version's folder in C:\(Windows)\Microsoft.NET\Framework\(dotnetver)\ (substituting the bracketed folders for the right folders on your PC) and run this command ```aspnet_regiis.exe -i ``` Next once that's run and finished, sometimes running ```iisreset ``` from the command line helps, sometimes you don't need to. Next, go to your IIS Manager and find you localhost website and choose add a folder. Browse to the folder in your project that contains the actual ASP.Net project and add that. Finally, 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. Please make sure the Virtual directory has the name 'MyWebApp'!! Reload your solution and it should work. Good luck!
I have a web project in my solution file that is "unavailable" when I open the solution. When I right-click on the web project and reload the project, I get the following error: ``` The Web Application Project mycompany.myapp.mywebproject is configured to use IIS. The Web Server 'http://localhost/MyWebApp could not be found. ``` I have not manually set up virtual directories for this web application. Per colleagues, Visual Studio should prompt me to create virtual directories but I am not getting prompted. I installed VS2010 before installing IIS on my dev machine. Here is my development machine setup: * Windows 7 Enterprise * Service Pack 1 * 64 bit OS * Visual Studio 2010 Enterprise Service pack 1 * IIS version 7.5
The walk cycle is considered to be one of the most basic aspects of animation. American animators and animation enthusiasts often times scorn the Japanese styles and methods of animation as lazy, while Japanese anime enthusiasts deride the American style as clunky or too comical. Why is that you ask? The answer lies in how these countries distribute their budget and time. While 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. In 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. A typical walk cycle in animation consists of 8 keyframes typically: The smoothness of an animation is typically determined by the framerate and amount of key frames in the animation. In 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. Japanese 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. Lets compare the difference between one walk cycle that is 8 frame to one that is 16 frames, both at 60 fps: Notice 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. The 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).
Why is it hard to draw people running in animes?
Faulty Premise #1: John the Baptist was a reincarnation of Elijah When Jesus asked Peter who people said he was, he answered that some people thought that Jesus was Elijah come back. Peter knew better and said Jesus was the Christ. In any event, John the Baptist himself directly denied the claim (see John 1:19-21). What 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. Note 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. Faulty Premise #2: The Jewish world view has any concept of reincarnation at all The 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. In 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. Furthermore, 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, It is appointed unto a man once to die and then the judgement. Here 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.
Malachi 4:5: I will send you the prophet Elijah. He will come before the day of the Lord arrives. It will be a great and terrifying day Jesus says in Matthew 11:14 "and if you are willing to believe their message, John is Elijah, whose coming was predicted" Jesus says in Mathew 17:12 But I tell you, Elijah 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.” It's pretty clear from the above verses that John was Elijah reincarnated. Wouldn't the above verses imply that reincarnation is true?
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). You 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. The 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. Footnote 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. Footnote 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.
I see hugely varied performance depending on how many newlines there are in the file I'm visiting. Here's an example. I have two JSON files: ```$ wget https://github.com/Wilfred/ReVo-utilities/blob/a4bdc40dd2656c496defc461fc19c403c8306d9f/revo-export/dictionary.json?raw=true -O one_line.json $ python -m json.tool pretty_printed.json ``` These 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. However, the bigger file split over many lines is much faster to open in Emacs, both in Javascript mode and Fundamental mode. Why 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?
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. Estimate, 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. If 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.
Sooner or later we come across a task in our project, with which we are totally unfamiliar ('we' as in PM, but also possibly the staff assigned to do this particular task). How can we estimate amount of time/work/resources needed to complete such a task? What margins of error should we assume?
Although English historians have defined Reich as being a strictly German concept of sovereign rule, in the German language itself it means "Empire". In English, we speak of the Holy Roman Empire; in German, it is the HRR or "Heiliges Römisches Reich Deutscher Nation". Wiktionary quotes Busching, who in 1762 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. One 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. Compare 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. If 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. (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) In 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. Nazi propagandists exploited this in their articles, making it sound as if the saints had had some sort of epiphany about Hitler and the Nazis. In 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. In 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. After 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.
Why is Nazi-Germany commonly referred to as "The Third Reich" in English? Why is reich not translated when Dritten ("third") is? And what is the English synonym of reich? Realm? Austria (Republik Österreich), Norway (Kongeriket Norge) and Sweden (Konungariket Sverige) all have reich (or the Norwegian/Swedish corresponding etymology related word) in their name and they all have English translations of their name.
Basically, a fold or crease in paper will remain because the structure of the fibers in the paper have become irreversibly damaged. This happens because the paper is bent/compressed beyond its elastic limit. Chemically, paper is mainly composed of cellulose from plant fibers. Cellulose is an organic polymer, which 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. All 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. Every 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. Now, 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. Because 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.
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?
Dennis Ritchie’s paper on The Development of the C Language gives some idea of the reasoning behind this: namely, the fundamental rule in C that declaration syntax should match expression syntax" For each object of such a composed type, there was already a way to mention the underlying object: index the array, call 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, ```int i, *pi, **ppi; ``` declare 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, ```int f(), *f(), (*f)(); ``` declare a function returning an integer, a function returning a pointer to an integer, a pointer to a function returning an integer; ```int *api[10], (*pai)[10]; ``` declare 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. It 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. It’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): ```sum(); ``` declares a ```sum``` function, which would then be defined as ```sum(a, b) { return a + b; } ``` (no types needed here, the default is ```int```). So the parser didn’t deal with types inside argument lists.
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```). One 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). When 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?
You have been told how to get a curved L. But here's some more general advice, which also applies in this situation: In cases such as this, always create your own shortcut macro, say ```\newcommand{\Lagr}{\mathcal{L}} ``` This way, if you ever decide that that curly L is not quite the one you like, it is easy to switch. Also, even before you knew the answer to this question, you could have written ```\newcommand{\Lagr}{L} ``` in 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. Another 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 ```\newcommand{\Lagr}{\mathop{\mathcal{L}}} ``` But in the case of operators, the package amsmath (which you are most likely using; if not, you should) provides a somewhat better mechanism: ```\DeclareMathOperator{\Lagr}{\mathcal{L}} ``` Another (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 ```\DeclareMathOperator{\Lagr}{\mathcal{L}} \DeclareMathOperator{\Lapl}{\mathcal{L}} ``` The 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.
I am new to TeX, working on it for about 2 months. Have not yet figured out how to script the 'curvy L' for Lagrangian and/or for Laplace Transforms. As of now I am using the 'L' - which is not good! :-( Any help? UPDATE The 2 best solutions are; ```\usepackage{ amssymb } \mathcal{L} ``` and ```\usepackage{ mathrsfs } \mathscr{L} ``` I got my answers at, http://detexify.kirelabs.org/classify.html
Welcome to the "Terrible Two's"! Your son behaves typically for his age. At 2 he starts to assert himself and express his demands. It's likely that he has also learned that he gets his way when he throws a tantrum. For a 2-year old screaming, hitting or even biting is a normal way to express his anger - at least he will try and every success reinforces this. He also comes across more limitations: The more he is able to do, the more often he is stopped. The solution? It's already in your question: He 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. * 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 ;-) * 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.) You have some serious work to do, but it will be sooooo worth it!
My son doesn't want to share anything with other kids, and if some kid even so much as touches his toy, he pushes the kid. He shouts and cries at the same time, and tries to express his anger by pushing and hitting the kid. I feel so embarrassed in front of other parents. And when he is at home with me and doing 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... Please help me how to stop him from being a bully.
The difference simply lies in that they solve different problems: * The State pattern deals with what (state or type) an object is (in) -- it encapsulates state-dependent behavior, whereas * the Strategy pattern deals with how an object performs a certain task -- it encapsulates an algorithm. The constructs for achieving these different goals are however very similar; both patterns are examples of composition with delegation. Some observations on their advantages: * 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. * 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. This likely also improves the context class' adherence to the single responsibility principle (SRP). Further the algorithm becomes easily available for reuse by other classes.
What are the differences between the Strategy design pattern and the State design pattern? please explain the difference in layman's terms?
There are 2 good reasons for this. First, a TT bike is the most efficient machine for flat, fast course racing, where there are a minimum of hills. It is not the most efficient machine when it comes to climbing. The body position is far too aggressive for even professional athletes to use in a non-TT style event. A 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. Secondly, 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. Or God forbid, permanently. For 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.
Why don't Tour de France riders always ride their TT bikes?
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. English 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. Nowadays, 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).
I remember when the Muslim holy book was the Koran when I was in middle school, but now it's the Quran. But it's always been Qatar and Iraq (but still Kuwait.) Who decided that 'Q' was going to be represent that sound instead of 'K', and why?
Put this in your `CMakeLists.txt` file (change any options from OFF to ON if you want): ``` set(Boost_USE_STATIC_LIBS OFF) set(Boost_USE_MULTITHREADED ON) set(Boost_USE_STATIC_RUNTIME OFF) find_package(Boost VERSION COMPONENTS *boost libraries here*) if(Boost_FOUND) include_directories(${Boost_INCLUDE_DIRS}) add_executable(progname file1.cxx file2.cxx) target_link_libraries(progname ${Boost_LIBRARIES}) endif() ``` Obviously 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: ``` find_package(Boost VERSION COMPONENTS filesystem regex) ```
How do you add Boost libraries in CMakeLists.txt?
Além do custo ser mais alto como mencionado, deve-se levar em conta vários fatores: * Volume de dados: para um baixo volume de dados pode não haver problema. Por outro lado, para armazenamento de grande massa de dados o banco de dados é praticamente inviável. Pergunte ao Facebook ou ao Google se eles usariam banco. O 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. * 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. * 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. * 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. * 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. * 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. Existem 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. Uma das grandes dificuldades em gerenciar arquivos fora do BD é que temos agora duas fontes de dados distintas e que precisam estar sempre em sincronia. Do 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. Porém, sempre que fiz a análise do melhor tipo de solução, o uso do sistema de arquivos sempre esteve em grande vantagem.
Quando devo fazer essa gravação direto no banco? Quais as situações? Eu sei que posso gravar no banco o caminho da imagem.
Here is the regular expression you can use: ``` /^\d*\.?\d*$/ ``` * `^` - Beginning of the line; * `\d*` - 0 or more digits; * `\.?` - An optional dot (escaped, because in regex, . is a special character); * `\d*` - 0 or more digits (the decimal part); * `$` - End of the line. This allows for .5 decimal rather than requiring the leading zero, such as 0.5
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
Assets * 1 obsolete piece of short range comms kit requiring a battery you probably can't charge * 1 slightly malfunctioning escape pod with up to date comms that isn't working but you're still alive Current standards say the Mayday should be broadcast on VHF channel 16 (156.8 MHz). A 1999 phone, probably on 2g would 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. Or you could look at the pod comms system and see what's wrong. Your 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. Or you could look at the pod comms system and see what's wrong. Now 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) I'm sure you can see where I'm going with this. Fix the pod. Ultimately 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. *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. ## Distress frequencies 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: ```121.5 MHz - civil aircraft emergency frequency 243 MHz - military aircraft emergency frequency 156.8 MHz - Marine VHF radio channel 16, short range maritime use 406 MHz / 406.1 MHz - Cospas-Sarsat international satellite-based search and rescue (SAR) distress alert detection and information distribution system ``` Discontinued frequencies ```500 kHz Morse code is no longer monitored. 121.5 or 243 MHz locators. (No longer automatically monitored by satellite, though still used for aircraft communication and short-range direction finding.) Effective 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. ```
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? Note: the cellphone was the most innovative product of 1999 money can buy. The 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. If there is absolutely no way to transmit any man-made signal out, please state a valid reason why it can't be done.
Situation 1: You're not looking through the camera yet * Fly Mode: Shift + F or the standard Viewport Navigation * Set Camera to View: Ctrl + Alt + Numpad 0 Situation 2: You're already looking through the camera via Numpad 0 * Select the camera: Right Mouse Button * Grab: G & optionally... * Lock the grab to a local axis: XX or YY or ZZ (my favorite) * Rotate: * Tilt: R * Look around: R R * Orbit around the 3D cursor: .R followed by R, or Z. (Press , afterwards) Tips & Notes (some go beyond this question): 1. 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. 2. 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: * Select the camera. * Shift-select the target. * 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.
Often I want to just point the camera to an object or a specific area in my scene to get an idea of how it'll look in the render. What's the most painless hassle-free way to do this in blender? A quick search on the blender wiki does not lend itself to easy look-up due to all the noise in the search result. This question could probably be broken down into these two main questions: * How do I point a selected camera to the current 3d-cursor location in the scene? * How do I point the selected camera to the currently selected object(s) in the scene?
At first glance Krav Maga and Systema seem to be very similar in that they are both very unconventional, no-rules, practical self-defence, martial arts (although Krav isn't technically a martial art) which are no holds barred and generally formless. However... Krav Maga is basically a very raw, dangerous situation 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. Systema 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. In Summary So 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. Also, 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/ KFM 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.
What are the general tactics of Krav Maga as opposed to Systema? For instance, the tactics of Silat are to hurt the other person so badly they can't hurt back. Another example would be that the tactics of boxing would be to knock out the other person first using only punches. So, as far as I know, the goal of Systema 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?
It's a security concern. The Android documentation doesn't provide a lot of elaboration, stating simply: The procedure must be confirmed on-screen, and deletes the user data for privacy reasons. However, the privacy concern is relatively straightforward to extrapolate. Once the bootloader is unlocked, the device 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: * Flashing a system image with root tools built in * Flashing a boot image that runs ```adbd``` with root by default (an "unsecure" image) * Flashing a recovery image, then using that to overwrite the system or boot partitions with ones that allow root access Once 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. Therefore, 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. Of 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.
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".
> The original IBM PC and later variants used an Intel 8253 or 8254 as a sound chip. The 8253 is a timer circuit, containing three timers able to generate timed interrupts or square-wave output with programmed frequencies. On the PC the third timer's output is, via an amplifier, connected to a simple speaker. As said before, calling a 'simple' timer a sound chip is quite a stretch. Since 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). Also, 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'. Of 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. > Why did users add sound cards such as the Adlib or Sound Blaster. Simply because they wanted sound - or at least music. Not just a beeper. > What was lacking with the original PC sound chip? As 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. Last 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. Addendum: agtoever 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. *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.
The original IBM PC and later variants used an Intel 8253 or 8254 as a sound chip. Why did users add sound cards such as the Adlib or Sound Blaster. I remember voice output with programs like telephone answering programs. The sound was wimpy but I attributed most of the quality to speaker size. What was lacking with the original PC sound chip?
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): ```struct callable_base { virtual int operator()(double d) = 0; virtual ~callable_base() {} }; template <typename F> struct callable : callable_base { F functor; callable(F functor) : functor(functor) {} virtual int operator()(double d) { return functor(d); } }; class function_int_double { std::unique_ptr<callable_base> c; public: template <typename F> function(F f) { c.reset(new callable<F>(f)); } int operator()(double d) { return c(d); } // ... }; ``` In 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. In 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. Regarding 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. ```// g++4.8 int main() { int value = 5; typedef std::function<void()> fun; fun f1 = [=]() mutable { std::cout << value++ << '\n' }; fun f2 = f1; f1(); // prints 5 fun f3 = f1; f2(); // prints 5 f3(); // prints 6 (copy after first increment) } ``` The 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.
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. An ```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?
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. Sacrament 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. Members 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. The 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. Counsel 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. Each 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. So 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.
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. Was 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? If someone could explain how instruction and exhortation are primarily conferred in the LDS church Id appreciate it.
Tres formas diferentes de hacerlo: 1. Utilizando la función ```String.split()``` : ``` String str = "123-654321"; String[] parts = str.split("-"); ``` Esta solución utiliza expresiones regulares, así que no es lo más eficiente si no estas trabajando con ellas. 2. Utilizando la clase ```StringTokenizer``` : ```static private List fastSplit(final String text, final String separator, final boolean emptyStrings){ List result = new ArrayList(); final StringTokenizer st = new StringTokenizer(text, separator, true); String token = null; String lastToken = separator; while (st.hasMoreTokens()) { token = st.nextToken(); if (token.equals(separator)) { if (lastToken.equals(separator) && emptyStrings) { result.add(""); } } else { result.add(token); } lastToken = token; } return result; } ``` El problema con este método es que solo funciona bien cuando el delimitador tiene longitud 1. 3. Implementarlo usando ```String.indexOf()``` : En este caso si funcionará correctamente para delimitadores de cualquier longitud. ```static private List fastSplit2(final String text, final String separator, final boolean emptyStrings) { final List result = new ArrayList(); if (text != null && text.length() > 0) { int index1 = 0; int index2 = text.indexOf(separator); int sepLen = separator.length(); while (index2 >= 0) { String token = text.substring(index1, index2); if (!token.isEmpty() || emptyStrings){ result.add(token); } index1 = index2 + sepLen; index2 = text.indexOf(separator, index1); } if (index1 < text.length() - 1) { result.add(text.substring(index1)); } } return result; } ```
A partir de un String, ```"123-654321"```, lo que deseo es dividirlo en dos Strings: ```string1=123 string2=654321 ```
In terms of ascii code, it's 3 -- since they're 10 and 13 respectively. But seriously, there are many differences: * in Unix and all Unix-like systems, ```\n``` is the code for end-of-line, ```\r``` means nothing special * as a consequence, in C and most languages that somehow copy it (even remotely), ```\n``` is the standard escape sequence for end of line (translated to/from OS-specific sequences as needed) * in old Mac systems (pre-OS X), ```\r``` was the code for end-of-line instead * in Windows (and many old OSs), the code for end of line is 2 characters, ```\r\n```, in this order * 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 * 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. * 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. In 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
What’s the difference between ```\n``` (newline) and ```\r``` (carriage return)? In particular, are there any practical differences between ```\n``` and ```\r```? Are there places where one should be used instead of the other?
There are a number of well-studied strategies; which is best in your application depends on circumstance. * Improve worst case runtime Using problem-specific insight, you can often improve the naive algorithm. For instance, there are $O(c^n)$ algorithms for Vertex Cover with $c huge improvement over the naive $\Omega(2^n)$ and might make instance sizes relevant for you tractable. * Improve expected runtime Using 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. * Restrict the problem If you can make more assumptions on your inputs, the problem may become easy. * Structural properties Your 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. * Bounding functions of the input Another 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. * Bounding input quantities Furthermore, 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. * Weaken the result This means that you tolerate errorneous or incomplete results. There are two main flavors: * Probabilistic algorithms You 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. * Approximation algorithms You 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. Refer to Algorithmics for Hard Problems by Hromkovič for a thorough treatment. * Simplicity is beauty: Improved upper bounds for vertex cover by Chen Jianer, Iyad A. Kanj, Ge Xia (2005)
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?
This is for safety reasons. Take-off and landing are the two most critical phases of flight and thus, every additional step to ensure survivability, be it even just adjusting the light, is taken. The interior lights or cabin lights are adjusted to match the exterior environment, so that in case of an emergency, 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. If 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. This 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. The 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.
Why are the lights inside commercial airplanes turned off during take off and landing?
There are 3 main ways to perform a case-insensitive search in Oracle without using full-text indexes. Ultimately what method you choose is dependent on your individual circumstances; the main thing to remember is that to improve performance you must index correctly for case-insensitive searching. 1. Case your column and your string identically. You can force all your data to be the same case by using `UPPER()` or `LOWER()`: ``` select * from my_table where upper(column_1) = upper('my_string'); ``` or ``` select * from my_table where lower(column_1) = lower('my_string'); ``` If `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. ``` create index my_index on my_table ( lower(column_1) ); ``` If you're using LIKE then you have to concatenate a `%` around the string you're searching for. ``` select * from my_table where lower(column_1) LIKE lower('my_string') || '%'; ``` 2. Use regular expressions. From Oracle 10g onwards `REGEXP_LIKE()` is available. You can specify the _match_parameter_ `'i'`, in order to perform case-insensitive searching. In 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. ``` select * from my_table where regexp_like(column_1, '^my_string$', 'i'); ``` In order to perform the equivalent of LIKE, these can be removed. ``` select * from my_table where regexp_like(column_1, 'my_string', 'i'); ``` Be careful with this as your string may contain characters that will be interpreted differently by the regular expression engine. 3. Change it at the session level. The 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. ``` alter session set nls_sort=BINARY_CI ``` There'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. You 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. So, once again, you need to alter the session ``` alter session set nls_comp=LINGUISTIC ``` You may want to create a linguistic index to improve performance ``` create index my_linguistc_index on my_table (NLSSORT(column_1, 'NLS_SORT = BINARY_CI')); ```
The default behaviour of ```LIKE``` and the other comparison operators, ```=``` etc is case-sensitive. Is it possible make them case-insensitive?
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. ## Detailed Answer JWT (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. Being 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. In 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. Regarding 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. One 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.
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? I 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.
Você pode fazer uploads de arquivos utilizando o método ```POST``` porém deve incluir o FormData com a propriedade ```enctype``` definida como ```multipart/form-data``` para que seus arquivos sejam enviados na requisição. Contudo, a formatação do envio não vai ser um JSON, mas sim no ```enctype``` que você definir no seu ```FormData```, que dependendo da linguagem que você está utilizando no backend vai ter uma forma diferente de interpretar estes dados. * 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; * multipart/form-data: nenhum caractere é convertido, mantendo os valores do formulário intactos, necessário para upload de arquivos; * text/plain: apenas espaços são convertidos em "+"; Sendo 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. Durante o upload você pode capturar (nos browsers modernos) evento de progresso do upload, conforme no exemplo abaixo. Exemplo utilizando **jQuery**: **Formulário** ```&lt;form id=&quot;formulario&quot; method=&quot;post&quot; enctype=&quot;multipart/form-data&quot;&gt; &lt;input type=&quot;text&quot; name=&quot;campo1&quot; value=&quot;hello&quot; /&gt; &lt;input type=&quot;text&quot; name=&quot;campo2&quot; value=&quot;world&quot; /&gt; &lt;input name=&quot;arquivo&quot; type=&quot;file&quot; /&gt; &lt;button&gt;Enviar&lt;/button&gt; &lt;/form&gt; ``` **Javascript** ```$("#formulario").submit(function() { var formData = new FormData(this); $.ajax({ url: window.location.pathname, type: 'POST', data: formData, success: function(data) { alert(data) }, cache: false, contentType: false, processData: false, xhr: function() { // Custom XMLHttpRequest var myXhr = $.ajaxSettings.xhr(); if (myXhr.upload) { // Avalia se tem suporte a propriedade upload myXhr.upload.addEventListener('progress', function() { /* faz alguma coisa durante o progresso do upload */ }, false); } return myXhr; } }); }); ```
Gostaria de saber se existe alguma forma simples de realizar um upload de arquivos via AJAX + JSON. Se houver, qual seria?
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. But 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. Sustainability 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.
Did the ancients or other pre-industrial civilisations engage in unsustainable practices?
There are 3 distinct (fairly) well-known Josephs in the Bible, firstly in the Old Testament (mainly): * Joseph the son of Jacob/Israel (aka The Patriarch Joseph). This Joseph is actually referred to in a few select places in the New Testament: John 4:5; Acts 7:9-18; Hebrews 11:21-22 & Revelation 7:8. However, it's more likely that a Joseph in the New Testament would be one of: * Joseph husband of Mary and surrogate father of Jesus (aka St. Joseph). * Joseph of Arimathea in whose tomb Jesus was laid to rest. There's also another 9 or 10 more obscure Josephs referred to in the Bible*, 4 more in the Old Testament*: * Father of Igal of the tribe of Issachar (cf. Numbers 13:7). * One of the "sons of Asaph" (cf. 1 Chronicles 25:2 & 9). * A descendant of Binnui, a contemporary of Ezra (cf. Ezra 10:38-42). * Head of the priestly family of Shekaniah, a contemporary of Nehemiah (cf. Nehemiah 12:14). And 5 or 6 more in the New Testament: * One of the (half-)brothers of Jesus (often translated as "Joses" - cf. Mark 6:3). * The son of "Mary" and brother of James (possibly/probably The Mary, if so, identical to Joseph number 8. - cf. Mark 15:40 & 47). * 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). * The son of Jonam (and father of Judah) also appearing in Luke's genealogy of Jesus (cf. Luke 3:30). * One of the nominees to replace Judas as an apostle, aka Barsabbas aka Justus (cf. Acts 1:23). * 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). *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).
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?
Ele é usado para garantir finalização de recursos adquiridos. Um arquivo, por exemplo é aberto. Quem garante que ele será fechado? Mesmo que você coloque no código de forma explícita que ele deve ser fechado, se ocorrer uma exceção, o código sai de escopo sem executar o resto do código que está em escopo, ele pula o fechamento. Para 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```. Ele 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. No exemplo citado deve ficar algo parecido com isto internamente: ```try: __enter__() open(&quot;my_file.txt&quot;) as file: data = file.read() #faça algo com &quot;data&quot; finally: __exit__() ```
Para que serve o "with" no Python?
The third Geneva convention says in its second article (emphasis added): > the present Convention shall apply to all cases of declared war or of any other armed conflict which may arise between two or more of the High Contracting Parties, even if the state of war is not recognized by one of them. > The Convention shall 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. The 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. It 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; As 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.
The question bothers me since February 2022. Why (legally) are Russian combatants in Ukraine considered soldiers (thus POWs when captured) rather than terrorists? * There is no formal declaration of war. * They are members an organization (Russian military) that commits acts of terrors to civilian population in clear violation of international law of war. Moreover, they either directly or indirectly contribute to the mentioned acts of terror. * Their state (Russia) explicitly claims that there is no war (thus unilaterally waiving the protection of law of war for Russian forces). Why 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? Note, that waiving the protection of law of war does not waive the protection of Ukrainian law (right to due process etc.).
The traditional branches of philosophy generally include * Aesthetics * Epistemology * Ethics * Logic * Metaphysics / Ontology We can go ahead and add a few contemporary branches on to this (more examples could certainly be adduced): * Philosophy of Science [referring to the hard sciences] (Mathematics, Technology, etc.) * Philosophy of Politics [referring to the social sciences] (Society, etc.) * 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] * Philosophy of Value (Axiology) * Philosophy of Language * Philosophy of Mind Philosophy 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. In addition, we could add many schools and movements (again, more examples could certainly be added). From the 20th century alone, there is: * Phenomenology (Husserl) * Schizoanalysis (Gilles Deleuze and Felix Guattari) * Chaosophy (Felix Guattari) * Non-philosophy (Francois Laruelle) * Existentialism (Sartre, et al.) * Vienna Circle/Logical Positivism Finally, 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: * Western philosophy * Ancient philosophy * Medieval philosophy * Renaissance philosophy * Modern philosophy * Contemporary philosophy * Eastern philosophy * Indian philosophy * Persian philosophy * Chinese philosophy * Japanese philosophy * Buddhist philosophy * Abrahamic philosophy * Jewish philosophy * Christian philosophy * Islamic philosophy
What are the major branches of philosophy?
There are several reasons, though not all of them would apply for one's usual holiday trip. 1. Remaining unseen: Obviously, during night its dark and this gives you a fair bit of cover if you want to remain unseen. This reason for traveling at night is common for many hunters in the animal kingdom (and sometimes also 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. 2. 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. 3. 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. 4. 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. 5. 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.
Are there any advantages while backpacking to hike during the night and sleep during the day?
Any sufficiently advanced technology is indistinguishable from magic. - Arthur C Clarke There's a reason that science fiction and fantasy are frequently shelved together - separating the two is usually a fools errand. The Dragonriders of Pern features a preindustrial society where flying, firebreathing, 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. In 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. The 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. ## Science fiction and fantasy are not a single genre - they are many Epic 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. In 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. The 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. If 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. On 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. If 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.
I have been cautioned against blending: * Traditional fantasy elements Such as magic systems and exotic, less plausible creatures (on a scientific level - magic tends to explain away these beasts) * Traditional sci-fi elements Such as advanced technology and civilizations amidst the stars. I have taken it upon 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) Why do people advise to stick to one or the other?
Proteases are enzymes in your digestive system that help break down food, acting like molecular-sized scissors that cut up proteins. Proteases have clefts, or subpockets, into which proteins fit, where the substrate (protein) gets cut. Infectious or pathogenic prions are resistant to proteases, because of their three-dimensional shape, which hides away parts of the prion that would normally fit in proteases and which would cause the prion to be digested. Prions 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: A 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). Dr. 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: Disease-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. To find out, Neena Singh and her team at Case Western Reserve University in Cleveland, Ohio, mimicked the process of eating and digesting infected meat. They 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. Prions, 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. The 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. Attaching to ferritin may provide additional protection from digestion, insofar as this removes prions from the digestive system, where proteases are concentrated.
Why are prions in animal diets not destroyed by the digestive system?
The syntax is: ``` a[start:stop] # items start through stop-1 a[start:] # items start through the rest of the array a[:stop] # items from the beginning through stop-1 a[:] # a copy of the whole array ``` There is also the `step` value, which can be used with any of the above: ``` a[start:stop:step] # start through not past stop, by step ``` The 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). The 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: ``` a[-1] # last item in the array a[-2:] # last two items in the array a[:-2] # everything except the last two items ``` Similarly, `step` may be a negative number: ``` a[::-1] # all items in the array, reversed a[1::-1] # the first two items, reversed a[:-3:-1] # the last two items, reversed a[-3::-1] # everything except the last two items, reversed ``` Python 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. ## Relationship with the ```slice``` object A slice object can represent a slicing operation, i.e.: ``` a[start:stop:step] ``` is equivalent to: ``` a[slice(start, stop, step)] ``` Slice 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)]```. While the ```:```-based notation is very helpful for simple slicing, the explicit use of ```slice()``` objects simplifies the programmatic generation of slicing.
How slicing in Python works? Please include references where appropriate.
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. So 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.
I am writing a story where a species undergoes devolution. Is there any scientific or plausible way to do this? The process can be instantaneous or may take ages, I do not mind which as I need to weigh my options at this stage. To be clear, the devolution I am thinking of is like taking a human being then devolving 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. Based on the answers, "devolution" does not exist so had the word in quotes to reflect this.
GEDCOM is the defacto standard for exchanging genealogical data. There are some problems with GEDCOM. * It is not rich enough to hold all the types of information that different vendor systems manage internally. So exporting GEDCOM from one system may lose information that that system actually holds. Though see point 4 below. * 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. * 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. * 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. There 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. A 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.
I've used GEDCOM to transfer data between desktop software and websites, but it all seems a bit old hat. Is there anything better that will mangle* my data less. * For example, GEDCOM can lose some data where the two ends of the system understand a concept which GEDCOM does not have a field for.
If you take advantage of how == works, you could simply create an object with a custom ```toString``` (or ```valueOf```) function that changes what it returns each time it is used such that it satisfies all three conditions. ``` const a = { i: 1, toString: function () { return a.i++; } } if(a == 1 && a == 2 && a == 3) { console.log('Hello World!'); } ``` The 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.
Is it ever possible that ```(a== 1 && a ==2 && a==3)``` could evaluate to true in JavaScript?
Já foi dito que ```string``` é apenas um alias para o tipo ```String```. Para deixar claro, não há diferença em performance ou forma como o código é gerado. Há exatamente zero diferença no tratamento de ambas. Elas podem fazer as mesmas coisas, e todos os membros estão disponíveis em qualquer um deles, afinal assim se comporta um alias. Diferenças úteis na utilização e escolha: * ```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. * ```string``` não pode ser usado com reflexão. ```String``` deve ser usado no lugar. * ```String``` pode ser usado para criar outros aliases: ``` using str = System.String; //... str s = &quot;Foi usado outro alias para string.&quot;; // a variável 's' é do tipo System.String que é o mesmo que ser string ``` Mas 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. * Há alguns locais que ocorre o oposto e criar um alias pode trazer mais legibilidade ao código. * Em outros casos pode ser apenas estranho usar um ou outro e dificultar a leitura. * 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á. * ```String``` pode ser usado como identificador válido. ```string``` é uma palavra reservada e não pode ser um identificador. * Há uma diferença na forma como o syntax highlight apresenta ambos. Pois uma forma é tipo e a outra é palavra chave. * 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). Mas 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. No CLR o estilo de case é usado para ajudar determinar outras características do identificador. * É 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. Importante 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```. També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. Importante notar que tudo isso é válido para o C#, outras linguagens como Java, ou até mesmo VB.NET podem ter mais diferenças. * Documentação oficial do ```string``` dizendo que é um alias. * FAQ reafirmando sobre aliases de tipos. * ```System.String```. Coloquei no GitHub para referência futura.
Gostaria de saber qual é a real diferença entre o ```String``` (s maiúsculo) e o ```string``` (s minúsculo). Aparentemente os dois têm os mesmos objetivos, porém qual é "melhor" para ser utilizado?
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 * 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) * 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) * 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) * If a fault is identified check if the cause is systemic and look at why it wasn't found in earlier tests or reviews This of course is useful when you are reviewing others code as well
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?
This largely comes down to whether your servers are ```pets``` or ```livestock```. Pets get individual names. They're distinct from each other, and we care about those differences. When one gets sick, we usually try to nurse it back to health. Traditionally, servers have been pets. Livestock get numbers. They're 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. In 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. Of 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.
Assume an environment with a puppet-managed cluster of different servers - various hardware, software, operating systems, virtual/dedicated, etc. Would you choose meaningful hostnames (mysqlmaster01..99, mysqlslave001..999, vpnprimary, vpnbackup, etc.) or would you prefer meaningless hostnames such as characters from a book or movie? The 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). Isn't mapping a service name to an IP address and maintaining that mapping what DNS is supposed to do? What are the advantages and drawbacks of both approaches and what actual problems have you had to tackle with the approach you chose?
First off, I highly recommend the book Get a Financial Life. The basics of personal finance and money management are pretty straightforward, and this book does a great job with it. It is very light reading, and it really geared for the young person starting their career. Now, with that out of the way, there's really two kinds of "investing" to think about: 1. Retirement (401k, IRA, SIMPLE, etc) 2. Non-Retirement (Brokerage account, investing in individual stocks, day trading, etc) For 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. There 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! Your 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.) ***The best way to start investing is to learn about your employer's retirement plan, and contribute enough to fully utilize the employer matching.*** Beyond 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. Keep 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. One 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.
Best way to start investing, for a young person just starting their career?
Quantum gate teleportation is the act of being able to apply a quantum gate on the unknown state while it is being teleported. This is one of the ways in which measurement-based computation can be described using graph states. Usually, teleportation works by having an unknown quantum state $|\psi\rangle$ held by Alice, 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. Let $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. Even 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. In 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.
Quantum state teleportation is the quantum information protocol where a qubit is transferred between two parties using an initial shared entangled state, Bell measurement, classical communication and local rotation. Apparently, there is also something called quantum gate teleportation. What is quantum gate teleportation and what is it used for? I am particularly interested in possible applications in simulating quantum circuits.
Mastering is a separate art from recording or mixing. According to the Wikipedia article, the principle processes of mastering are: * Editing minor flaws. * Applying noise reduction to eliminate clicks, dropouts, hum and hiss. * Adjusting stereo width. * Adding ambience. * Equalize audio across tracks for the purpose of optimized frequency distribution. * Adjust volume. * Dynamic range compression or expansion. * Peak limit. * Dither. The 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. As 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.
What does it mean for an album to be remastered?
Extracted from the reference How to Iterate Over a Map in Java: There are several ways of iterating over a ```Map``` in Java. Let's go over the most common methods and review their advantages and disadvantages. Since all maps in Java implement the Map interface, the following techniques will work for any map implementation (```HashMap```, ```TreeMap```, ```LinkedHashMap```, ```Hashtable```, etc.) Method #1: Iterating over entries using a For-Each loop. This 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. ```Map map = new HashMap(); for (Map.Entry entry : map.entrySet()) { System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); } ``` Note 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. Method #2: Iterating over keys or values using a For-Each loop. If you need only keys or values from the map, you can iterate over keySet or values instead of entrySet. ```Map map = new HashMap(); // Iterating over keys only for (Integer key : map.keySet()) { System.out.println("Key = " + key); } // Iterating over values only for (Integer value : map.values()) { System.out.println("Value = " + value); } ``` This method gives a slight performance advantage over ```entrySet``` iteration (about 10% faster) and is more clean. Method #3: Iterating using Iterator. Using Generics: ```Map map = new HashMap(); Iterator> entries = map.entrySet().iterator(); while (entries.hasNext()) { Map.Entry entry = entries.next(); System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); } ``` Without Generics: ```Map map = new HashMap(); Iterator entries = map.entrySet().iterator(); while (entries.hasNext()) { Map.Entry entry = (Map.Entry) entries.next(); Integer key = (Integer)entry.getKey(); Integer value = (Integer)entry.getValue(); System.out.println("Key = " + key + ", Value = " + value); } ``` You can also use same technique to iterate over ```keySet``` or values. This 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. From a performance point of view this method is equal to a For-Each iteration. Method #4: Iterating over keys and searching for values (inefficient). ```Map map = new HashMap(); for (Integer key : map.keySet()) { Integer value = map.get(key); System.out.println("Key = " + key + ", Value = " + value); } ``` This 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. Conclusion: If 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.
What's the best way to iterate over the items in a ```HashMap```?
CO2 tastes good! Carbonated water is actually a weak carbonic acid solution; this is what you taste. It's like "salt and pepper", but for water. Slightly acidic water is usually popular, hence lemon juice is sometimes used to taint a jug of water in times when no carbonated water is available. Carbonated water 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. In 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. Around 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. Nitrogen 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. Oxygen 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. In 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.
Why did people start using CO2 (instead of e.g. oxygen) for carbonated drinks?
You are using ```|``` (pipe) to direct the output of a command into another command. What you are looking for is ```&&``` operator to execute the next command only if the previous one succeeded: ```cp /templates/apple /templates/used && cp /templates/apple /templates/inuse && rm /templates/apple ``` Or ```cp /templates/apple /templates/used && mv /templates/apple /templates/inuse ``` To summarize (non-exhaustively) bash's command operators/separators: * ```|``` 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. * ```|&```pipes both ```stdout``` and ```stderr``` of one command into the standard input of another one. Very useful, available in bash version 4 and above. * ```&&``` executes the right-hand command of ```&&``` only if the previous one succeeded. * ```||``` executes the right-hand command of ```||``` only it the previous one failed. * ```;``` 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.
Say I have a file ```/templates/apple``` and I want to * put it in two different places and then * remove the original. So, ```/templates/apple``` will be copied to ```/templates/used``` AND ```/templates/inuse``` and then after that I’d like to remove the original. Is ```cp``` the best way to do this, followed by ```rm```? Or is there a better way? I want to do it all in one line so I’m thinking it would look something like: ```cp /templates/apple /templates/used | cp /templates/apple /templates/inuse | rm /templates/apple ``` Is this the correct syntax?
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. The 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: * 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$. * The induced width of the constraint graph of the problem is small. * For a MIP model, the constraint matrix has a small bandwidth. * For knapsack-like problems, the maximum `budget' is relatively small. Note 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. There are several areas of combinatorial optimization in which decision diagrams have been successfully applied: * 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. * 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. * Graph-theoretic problems. Examples include set covering, maximum independent set, and maximum cut. * 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.
When are Decision Diagrams the right way to model and solve a problem?
Sounds like a great idea! Seriously though: the antagonist is the single most important character to any plot. The very best antagonists have motivations and feelings that readers can understand and empathize with. A former protagonist as an antagonist sounds really good. Both the reader and the author should be in 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". Think 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. Imagine 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.
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. My question: Should 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?
Anycast is networking technique where the same IP prefix is advertised from multiple locations. The network then decides which location to route a user request to, based on routing protocol costs and possibly the 'health' of the advertising servers. There are several benefits to anycast. First, in steady state, users 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). Another 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. Depending 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. A 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.
I'd never heard of anycast until a few seconds ago when I read "What are some cool or useful server/networking tricks?". The wikipedia "Anycast" article on it is quite formal and doesn't really evoke a mental picture of how it would be used. Can someone explain in a few informal sentences what "anycast" is, how you configure it (just in a general sense), and what its benefits are (what does it make easier)?
Except for code which does a significant number of floating-point operations on data that are held in cache, most floating-point intensive code is performance limited by memory bandwidth and cache capacity rather than by flops. $v$ and the products $Av$ and $Bv$ are all vectors of length 2000 (16K bytes in double 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. Computing $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. Computing $(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. Thus there's twice as much memory traffic involved in computing this as $(A+B)v$ instead of $Av+Bv$. Note 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.
$A$ and $B$ are $n \times n$ matrices and $v$ is a vector with $n$ elements. $Av$ has $\approx 2n^2$ flops and $A+B$ has $n^2$ flops. Following this logic, $(A+B)v$ should be faster than $Av+Bv$. Yet, when I run the following code in matlab ```A = rand(2000,2000); B = rand(2000,2000); v = rand(2000,1); tic D=zeros(size(A)); D = A; for i =1:100 D = A + B; (D)*v; end toc tic for i =1:100 (A*v+B*v); end toc ``` The opposite is true. Av+Bv is over twice as fast. Any explanations?
## How to find it out That's the address of a label and it's a feature specific to GCC. ```int main(void) { void* startp; s: startp = &&s; printf(&quot;the assignment above starts at address %p\n&quot;, startp); return 0; } ``` You could have figured it out yourself by testing: ```int main(void) { void* startp; int a; startp = &&a; printf(&quot;startp=%p\n&quot;, startp); return 0; } ``` In which case GCC says: > error: label ‘a’ used but not defined ## Under the hood - assembly You need to know assembler to really understand this, but I'll try to explain you what an address of a label means. After 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. This 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). (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) Now, 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. After 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. You can inspect this with: ``` objdump -x a.out ```
I came across a piece of code ```void *p = &&abc;```. What is the significance of ```&&``` here? I know about rvalue references but I think ```&&``` used in this context is different. What does ```&&``` indicate in ```void *p = &&abc;``` ?
You can use ```isatty```: ``` #include <stdio.h> #include <io.h> ... if (isatty(fileno(stdin))) printf( "stdin is a terminal\n" ); else printf( "stdin is a file or a pipe\n"); ``` On windows they're prefixed with underscores: ```_isatty```, ```_fileno```.
When I execute "```python```" from the terminal with no arguments it brings up the Python interactive shell. When I execute "```cat | python```" from the terminal it doesn't launch the interactive mode. Somehow, without getting any input, it has detected that it is connected to a pipe. How would I do a similar detection in C or C++ or Qt?
The easy-to-spot stuff: * (assumed) Improper transportation of hazardous materials. Both white fuming nitric acid and furfuryl alcohol are considered hazardous materials; none of the vehicles in the video appears to have a hazmat placard, the rocket is not an approved hazmat container, and the fuel containers seen in other videos are emphatically not approved. * 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. * 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. * Bad angle when lifting the test object upright. This puts excess loads on things, increasing the risk of a fall or failure. * Using unbraced legs as a pivot point when lifting the test object upright. You can see they're on the verge of buckling. * (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. * Having people stand under a suspended load. If the test object falls, this will cause serious injury or death to at least two people. * Using a truck to pull the lifting cable. This provides far less control than a proper winch. * 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. * 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. * Having unnecessary equipment in the test area. In the event of a failure, this can become additional flying debris. * 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. * 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. * (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. * 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. * 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. * (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.
"The video of Pythom Space's first rocket test has raised a few eyebrows The video prompted hundreds of replies on Twitter, including some from rather horrified rocket scientists. &quot;We knew better as untrained college students,&quot; said Jordan Noone, the co-founder of Relativity Space. Pythom “Micro jump” What exactly did they get wrong with this test? Note: 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)"
The ```wp_register_script()``` Codex page literally says: A safe way of registering javascripts in WordPress for later use with ```wp_enqueue_script()```. This means, if you want to register your scripts, but not directly load them in your pages, you can register the files once, and then load them when you need them. For example: You 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: ```... wp_register_script( 'my-handy-javascript', ... ); ... switch( $somevar ) { case 'value': wp_enqueue_script( 'my-handy-javascript' ); // needs the file ... break; case 'value2': wp_enqueue_script( 'my-handy-javascript' ); // needs the file ... break; default: case 'value3': // doesn't needs the file ... break; } ``` It 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. The Codex also tells the following: Use the ```wp_enqueue_scripts``` action to call this function, or ```admin_enqueue_scripts``` to call it on the admin side. This 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```. This way you won't have the same enqueue recourse twice in one theme, plugin, widget or whatever.
When should I use wp_register_script() with wp_enqueue_script() vs just wp_enqueue_script()?
> What are the advantages and limitations of the various approaches? * Pros of deep embeddings : You can prove and define things by induction on formulas' structure. Examples of interests are the size of a formula. * Cons of deep embeddings: You have do deal explicitly with binding of variables. That's usually very laborious. > Are there any guidelines available for determining which to use ? Shallow 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. On the other side, deep embedding are almost mandatory when you want to prove meta-theorems about the object logic (like cut-elimination for instance). > Is it possible to switch between the two representations in any systematic fashion? The 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. So it is possible to send every result obtained in a deep embedding setting through an interpretation function. Here is a little coq example: ``` Inductive formula : Set := Ftrue : formula | Ffalse : formula | Fand : formula -> formula -> formula | For : formula -> formula -> formula. Fixpoint interpret (F : formula) : Prop := match F with Ftrue => True | Ffalse => False | Fand a b => (interpret a) /\ (interpret b) | For a b => (interpret a) \/ (interpret b) end. Inductive derivable : formula -> Prop := deep_axiom : derivable Ftrue | deep_and : forall a b, derivable a -> derivable b -> derivable (Fand a b) | deep_or1 : forall a b, derivable a -> derivable (For a b) | deep_or2 : forall a b, derivable b -> derivable (For a b). Inductive sderivable : Prop -> Prop := shallow_axiom : sderivable True | shallow_and : forall a b, sderivable a -> sderivable b -> sderivable (a /\ b) | shallow_or1 : forall a b, sderivable a -> sderivable (a \/ b) | shallow_or2 : forall a b, sderivable b -> sderivable (a \/ b). (* You can prove the following lemma: *) Lemma shallow_deep : forall F, derivable F -> sderivable (interpret F). (* You can NOT prove the following lemma :*) Lemma t : forall P, sderivable P -> exists F, interpret F = P. ```
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. * What are the advantages and limitations of the various approaches? * Are there any guidelines available for determining which to use? * Is it possible to switch between the two representations in any systematic fashion? As 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.
Let's start with a quick review of "countable". A set is countable if we can set up a 1-1 correspondence between the set and the natural numbers. As an example, let's take $\mathbb{Z}$, which consists of all the integers. Is $\mathbb Z$ countable? It may seem uncountable if you pick a naive correspondence, say $1 \mapsto 1$, $2 \mapsto 2 ...$, which leaves all of the negative numbers unmapped. But if we organize the integers like this: $$0$$ $$1, -1$$ $$2, -2$$ $$3, -3$$ $$...$$ We 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. We 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": 1. "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$. 2. "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$. 3. "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 ...$ So 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: $$s_{11}, s_{12}, s_{13} ...$$ $$s_{21}, s_{22}, s_{23} ...$$ $$s_{31}, s_{32}, s_{33} ...$$ $$...$$ Now 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. Let'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?
Prove that the union of countably many countable sets is countable.
Muito da polêmica ocorre pela falta de uma contextualização. Não vejo nada que desabone o padrão Sigleton quando usado no contexto correto. Sim, ele pode causar muito mal, assim como qualquer padrão de projeto aplicado indevidamente sem análise do impacto e dos efeitos colaterais. ###Porque não usar * Acoplamento. Ao 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. * 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ã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. No 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. ###Porque usar Em 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. També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. ###Como usar Quando 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ê! ###Como evitar o Singleton Apesar 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.
Você encontra na internet a afirmação que Singletons são ruins. Isto é verdade? Por quê? O problema seria generalizado para quaisquer objetos com instância única? Ou para qualquer coisa que tenha estado global? Se é tão ruim, pra que foi inventado? Ou seja, que problema ele queria resolver? Quais os problemas que terei se usá-lo? Existe alternativa viável?
To start with, compare the circle the diameter we're given would make with the circle the circumference we're given would make: Since a circumference is π times the diameter, a 'pure' circle of 10 cubits in diameter as we describe the sea as having would be 10π cubits in circumference, or roughly 31.4 cubits. Now, 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. Or to tabulate it: ```Circle A: ~9.55 cubits diameter, 30 cubits circumference Circle B: 10 cubits diameter, ~31.4 cubits circumference ``` Given that, we have two diameters differing by about .45 cubits (about eight inches on an 18-inch cubit--a sizable difference). Since 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. Dividing 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. Do we have any authority for assuming that this is the case and saying the sea was anything like four inches thick? A couple of verses after this we have 1 Kings 7:26, which gives it to us outright: 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. A handbreadth as a unit of measurement is generally given as between three and four inches. (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.)
The construction of Solomon's temple includes a piece of furnishing described in 1 Kings 7:23 (ESV): Then he made the sea of cast metal. It was round, ten cubits from brim to brim, and five cubits high, and a line of thirty cubits measured its circumference. So if the ```diameter = 10``` cubits and the ```circumference = 30``` cubits, then ```π = 3``` by the equation ```C = π * D```. Of 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?
* For your first two example cases, you could use ```key()``` and ```current()``` to assign the values you need. ```$ar = $o->me; // reset isn't necessary, since you just created the array $typ = key($ar); $val = current($ar); ``` * ```$out = array('me' => array(), 'mytype' => 2, '_php_class' => null); $expected = [key($out), current($out)]; ``` In 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. * For the third case, I'd suggest just using a ```foreach()``` loop instead and assigning ```$kv``` inside the loop. ```foreach ($broken as $k => $v) { $kv = [$k, $v]; } ``` * For the fourth case, it looks like the key is disregarded in ```list()```, so you can assign the current value. ```$this->result = current($this->cache_data); ``` Like 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```. * Fifth can be replaced with a ```for()``` loop. ```reset($array); for ($i = 0; $i < 30; $i++) { $id = key($array); $item = current($array); // code next($array); } ```
With PHP 7.2, ```each``` is deprecated. The documentation says: Warning This function has been DEPRECATED as of PHP 7.2.0. Relying on this function is highly discouraged. How can I update my code to avoid using it? Here are some examples: * ```$ar = $o->me; reset($ar); list($typ, $val) = each($ar); ``` * ```$out = array('me' => array(), 'mytype' => 2, '_php_class' => null); $expected = each($out); ``` * ```for(reset($broken);$kv = each($broken);) {...} ``` * ```list(, $this->result) = each($this->cache_data); ``` * ```// iterating to the end of an array or a limit > the length of the array $i = 0; reset($array); while( (list($id, $item) = each($array)) || $i < 30 ) { // code $i++; } ``` When I execute the code on PHP 7.2 I receive the following error: Deprecated: The each() function is deprecated. This message will be suppressed on further calls
Sure, here are different preparations of eggs: 1. Fried Eggs: * Sunny Side Up -- Not flipped, unbroken yolk. The top of the egg is just barely set. * Basted -- Sunny Side Up, hot fat spooned over until the white surrounding the yolk is opaque. * Over Easy / lite -- Flipped, whites fully cooked, unbroken yolk, yolk runny. * Over medium -- flipped, whites fully cooked, unbroken yolk, yolk creamy (not completely runny). * Over Medium Well -- Flipped, unbroken yolk, yolk cooked to have a firm but wet-appearing center. * Over Hard -- Flipped, broken, fully-cooked yolk. * Over Well -- Flipped, intact, fully-cooked yolk. * Broken / Lightly Scrambled -- Broken in pan and gently stirred while cooking - yolk and whites should not be mixed entirely. * 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. 2. Omelettes: * 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. * 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. * 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). * 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. 3. Boiled: Cooked 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. * Soft -- Yolk runny, potentially with slight unset white around the yolk. * Medium -- White completely set, yolk firm but with a dark, wet appearance. * Hard -- Yolk completely set and pale yellow. 4. Poached: Egg 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. 5. Coddled: An 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. 6. Shirred: An 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. 7. Steamed: Very similar to shirred eggs, but the ramekin is covered with some aluminum foil and put in a steamer for 7-15 minutes. 8. In a basket: Eggs fried in a hole made in a slice of bread. 9. deep fried Moo 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.
Can someone please give an explanation of different egg preparations?
It depends on the tax system that applies to you, but there can be consequences, and they can be very severe. Generally economic activity is defined as oriented on profit, so giving anything for free could qualify as self-promotion or donation. In Poland, for example, only some costs of the company spend on promotion 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. With 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. There 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. Assuming, analyse your local law, consult a tax specialist and be sure you exactly want what you are doing before issuing €0 invoices.
I'm running a relatively small one-man business in the software sector. I just started and am trying to create a larger portfolio. For that, I offer some friends free services. I found a few reasons to send these clients €0,- invoices, mostly similar to the reasons to send 100% discount invoices to charity funds that I gave here: * Clarity about what has to be done and when * No transfers (as I would have with a 0% discount bill and returning the money as a gift) And also: * 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) Suppose that these clients won't have a problem with the €0,- invoices, could there be any reason for me to not send them? I ask this, because I've never seen people sending invoices like this, and I can only see advantages.
The first one should never be used in production code, since it's transporting information irrelevant to end-users (a user can't do anything about "Cannot connect to database"). You throw Exceptions if you know that at a certain critical code point, your application can fail and you want your code to recover across multiple call-levels. ```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. Also ```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: ```// Example (pseudo-code for db queries): $db->query('START TRANSACTION'); try { while ($row = gather_data()) { $db->query('INSERT INTO `table` (`foo`,`bar`) VALUES(?,?)', ...); } $db->query('COMMIT'); } catch(Exception $e) { $db->query('ROLLBACK'); } ``` Here, 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.
In regards to Error handling in PHP -- As far I know there are 3 styles: * ```die()```or ```exit()``` style: ```$con = mysql_connect("localhost","root","password"); if (!$con) { die('Could not connect: ' . mysql_error()); } ``` * ```throw Exception``` style: ``` if (!function_exists('curl_init')) { throw new Exception('need the CURL PHP extension. Recomplie PHP with curl'); } ``` * ```trigger_error()``` style: ```if(!is_array($config) && isset($config)) { trigger_error('Error: config is not an array or is not set', E_USER_ERROR); } ``` Now, in the PHP manual all three methods are used. * What I want to know is which style should I prefer & why? * Are these 3 drop in replacements of each other & therefore can be used interchangeably? Is it just me or everyone thinks PHP error handling options are just too many to the extent it confuses php developers?
Here is the solution, but be careful if you have a multi-user repository - this will change all commits to have the same (new) author and committer. ``` git filter-branch -f --env-filter " GIT_AUTHOR_NAME='Newname' GIT_AUTHOR_EMAIL='new@email' GIT_COMMITTER_NAME='Newname' GIT_COMMITTER_EMAIL='new@email' " HEAD ``` Changing 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. Specifically, you can fix all the wrong author names and emails for all branches and tags with this command (source: GitHub help): ``` #!/bin/sh git filter-branch --env-filter ' OLD_EMAIL="your-old-email@example.com" CORRECT_NAME="Your Correct Name" CORRECT_EMAIL="your-correct-email@example.com" if [ "$GIT_COMMITTER_EMAIL" = "$OLD_EMAIL" ] then export GIT_COMMITTER_NAME="$CORRECT_NAME" export GIT_COMMITTER_EMAIL="$CORRECT_EMAIL" fi if [ "$GIT_AUTHOR_EMAIL" = "$OLD_EMAIL" ] then export GIT_AUTHOR_NAME="$CORRECT_NAME" export GIT_AUTHOR_EMAIL="$CORRECT_EMAIL" fi ' --tag-name-filter cat -- --branches --tags ``` For using alternative history filtering tool `git filter-repo`, you can first install it and construct a `git-mailmap` according to the format of `gitmailmap`. ``` Proper Name <proper@email.xx> Commit Name <commit@email.xx> ``` And then run filter-repo with the created mailmap: ``` git filter-repo --mailmap git-mailmap ```
How do I change the author and committer name/email for multiple commits?
In increasing order of complexity and price you have, * Personal Locator Beacons Personal locator beacons are high-powered (typically, 5 watts) devices designed primarily to send out a personalized emergency distress signal. They generally require an open view of the sky to transmit successfully. * Satellite Messengers (Like a Garmin inReach) 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. * Satellite Phones 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. None 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.
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?