658 Matching Annotations
  1. Apr 2023
    1. Here we have extended this model to a slightly different category, a category where morphisms are represented by embellished functions, and their composition does more than just pass the output of one function to the input of another. We have one more degree of freedom to play with: the composition itself. It turns out that this is exactly the degree of freedom which makes it possible to give simple denotational semantics to programs that in imperative languages are traditionally implemented using side effects.
    2. For our limited purposes, a Kleisli category has, as objects, the types of the underlying programming language. Morphisms from type A to type B are functions that go from A to a type derived from B using the particular embellishment. Each Kleisli category defines its own way of composing such morphisms, as well as the identity morphisms with respect to that composition.
  2. Feb 2023
    1. There is just one little nit for mathematicians to pick: morphisms don’t have to form a set. In the world of categories there are things larger than sets. A category in which morphisms between any two objects form a set is called locally small.
    2. It’s worth emphasizing that Haskell lets you express equality of functions, as in: mappend = (++) Conceptually, this is different than expressing the equality of values produced by functions, as in: mappend s1 s2 = (++) s1 s2 The former translates into equality of morphisms in the category Hask (or Set, if we ignore bottoms, which is the name for never-ending calculations). Such equations are not only more succinct, but can often be generalized to other categories. The latter is called extensional equality, and states the fact that for any two input strings, the outputs of mappend and (++) are the same. Since the values of arguments are sometimes called points (as in: the value of f at point x), this is called point-wise equality. Function equality without specifying the arguments is described as point-free. (Incidentally, point-free equations often involve composition of functions, which is symbolized by a point, so this might be a little confusing to the beginner.)
    3. Is composition associative? Check!

      Associativity for <= seems a bit weird to me; generally you want the value inside of () to be comparable outside; but (1 <= 2) <= 3 would result in True <= 3. So I think the best way to think of associativity here is that it just does not apply, and the () can be dropped.

    4. Let’s characterize these ordered sets as categories. A preorder is a category where there is at most one morphism going from any object a to any object b. Another name for such a category is “thin.” A preorder is a thin category.
    5. A set of morphisms from object a to object b in a category C is called a hom-set and is written as C(a, b) (or, sometimes, HomC(a, b)). So every hom-set in a preorder is either empty or a singleton. That includes the hom-set C(a, a), the set of morphisms from a to a, which must be a singleton, containing only the identity, in any preorder. You may, however, have cycles in a preorder. Cycles are forbidden in a partial order.
    1. The effects of four reference antihistamines: ketotifen, diphenhydramine, chlorpheniramine and pyrilamine and of astemizole, a new potent and long-acting antihistamine, were studied on 16 hr sleep-wakefulness patterns in the same dogs. Using a computer-based on-line analysis and automatic stage classification, a differentiation was made between wakefulness, transition to sleep (drowsiness), slow wave sleep and rapid eye movement (REM) sleep. The reference antihistamines significantly increased non-REM sleep. The reference antihistamines significantly increased non-REM sleep: diphenhydramine and chlorpheniramine increased drowsiness, ketotifen increased slow-wave sleep and pyrilamine increased both. All, but astemizole, significantly prolonged the latency to the first REM period, prolonged the interval between successive REM periods and suppressed the total amount of REM sleep. With all antihistamines, the effects were most pronounced for the first 4 hr and there was no within-night rebound. Chlorpheniramine had long-lasting effects throughout the night, especially on REM sleep. The effects on non-REM sleep might be due to a blockage of brain histamine H1 receptors, whereas the effects on REM sleep might be due to the anticholinergic properties of the antihistamines. Astemizole was devoid of any significant effect on the sleep-wakefulness pattern, in spite of its long-lasting antihistamine effects, suggesting that the common clinical side-effects of antihistamines, such as sedation and dryness of mucosal surfaces, will be lacking.

      It may be worth exploring the improvements on non-REP sleep, particularly if they are increasing slow wave (deep) sleep. This is particularly true, since newer generations of antihistamines aren't anticholinergic.

    1. When threatened with the possibility of starvation, early humans developed a survival response which sent them foraging for food. Yet foraging is only effective if metabolism is inhibited in various parts of the brain.Foraging requires focus, rapid assessment, impulsivity, exploratory behavior and risk taking. It is enhanced by blocking whatever gets in the way, like recent memories and attention to time. Fructose, a kind of sugar, helps damp down these centers, allowing more focus on food gathering.In fact, the researchers found the entire foraging response was set in motion by the metabolism of fructose whether it was eaten or produced in the body. Metabolizing fructose and its byproduct, intracellular uric acid, was critical to the survival of both humans and animals.The researchers noted that fructose reduces blood flow to the brain’s cerebral cortex involved in self-control, as well as the hippocampus and thalamus. Meanwhile, blood flow increased around the visual cortex associated with food reward. All of this stimulated the foraging response.

      Seems like fasting may be beneficial:

      The researchers found cerebral fructose levels rose significantly in response to a glucose infusion, with minimal changes in fructose levels in the blood. They surmised that the high concentration of fructose in the brain was due to a metabolic pathway called the polyol pathway that converts glucose to fructose.

      And from elsewhere, as seems to be common knowledge:

      In prolonged fasting, the brain derives a large portion of its oxidative energy from the ketone bodies, beta-hydroxybutyrate and acetoacetate, thereby reducing whole body glucose consumption.

      See also: 1. Fasting-Mimicking Diet Reduces Signs of Dementia

    2. Johnson suspects the survival response, what he calls the “survival switch,” that helped ancient humans get through periods of scarcity, is now stuck in the “on” position in a time of relative abundance. This leads to the overeating of high fat, sugary and salty food prompting excess fructose production.Fructose produced in the brain can lead to inflammation and ultimately Alzheimer’s disease, the study said. Animals given fructose show memory lapses, a loss in the ability to navigate a maze and inflammation of the neurons.“A study found that if you keep laboratory rats on fructose long enough they get tau and amyloid beta proteins in the brain, the same proteins seen in Alzheimer’s disease,” Johnson said. “You can find high fructose levels in the brains of people with Alzheimer’s as well.”Johnson suspects that the tendency of some AD patients to wander off might be a vestige of the ancient foraging response.
    1. In this study, an at least 30-fold margin between hERG’s half maximal inhibitory concentration (IC50; indicates the quantity of substance needed to inhibit a given biological process in vitro by 50%) and the maximal concentration after 1 dose of cannabidiol (Cmax) has been proposed to be an acceptable degree of safety from arrhythmogenesis.5 There are human pharmacokinetic data showing that the Cmax values for CBD can reach 0.35–0.58 μM after smoking (19.2 mg) and oral intake (400 mg), respectively.6 Based on Orvos and colleagues,5 who showed that CBD had an inhibitory effect on hERG channel activity with an IC50 value of 2.07 μM, the ingestion of 400 mg of CBD results in a ratio of 3.57 (<30), thus suggesting the potential of proarrhythmic side effects in humans, especially in case of interactions with the metabolism of CBD.6 In vitro, CBD inhibits CYP isozymes (mainly CYP3A4 and CYP2C19),7 but it is unclear whether this occurs at concentrations achieved with doses used clinically.

      see here for an example calculation (confirm later)

      The study reporting on Cmax states:

      Cmax and AUC following oral administration also appears to be dose dependent. A dose of 10 mg CBD resulted in mean Cmax of 2.47 ng/mL at 1.27 h, and a dose of 400 or 800 mg co-administered with i.v. fentanyl (a highly potent opioid) to examine its safety resulted in a mean Cmax of 181 ng/mL (at 3.0 h) and 114 ng/mL (at 1.5 h) for 400 mg, and 221 ng/mL (at 3.0 h) and 157 ng/mL (at 4.0 h) for 800 mg, in 2 sessions, respectively (Guy and Robson, 2004b; Manini et al., 2015). A dose of 800 mg oral CBD in a study involving 8 male and female cannabis smokers, reported a mean Cmax of 77.9 ng/mL and mean Tmax of 3.0 h (Haney et al., 2016). Although, an increase in dose corresponds with an increase in Cmax, the Cmax between the higher doses of CBD does not greatly differ, suggesting a saturation effect (e.g., between 400 and 800 mg). One hour after oral capsule administration containing 5.4 mg CBD in males and females, mean Cmax was reported as 0.93 ng/mL (higher for female participants than male) (Nadulski et al., 2005a). A subset (n = 12) consumed a standard breakfast meal 1 h after the capsules, which slightly increased mean Cmax to 1.13 ng/mL. CBD remained detectable for 3–4 h after administration (Nadulski et al., 2005b). Cherniakov et al. examined the pharmacokinetic differences between an oromucosal spray and an oral capsule with piperine pro-nanolipospheres (PNL) (both 10 mg CBD) in 9 men. The piperine-PNL oral formulation had a 4-fold increase in Cmax (2.1 ng/mL vs. 0.5 ng/mL), and a 2.2-fold increase in AUC0−t (6.9 vs. 3.1 h × ng/mL), while Tmax was decreased (1.0 vs. 3.0 h) compared to the oromucosal spray (Cherniakov et al., 2017a). This group further developed self-emulsifying formulations and reported again an increased bioavailability and increased Cmax within a shorter time compared to a reference spray (Atsmon et al., 2017a,b).

    1. It’s different for everyone. I have found it to be amazing. It has given me energy, drive, motivation, euphoria, happiness, mood enhancement, and more endurance. It also makes music super awesome to listen to, with a physical and mental high. The difference bw this and any benzo is that they target different things. Benzodiazepines target a binding point found on certain GABA-A receptors and it enhances GABA by modulating it (increasing GABA’s overall effectiveness and activity), and there are more than one binding points that benzodiazepines can bind to (BZD1, BZD2, etc) that cause different effects like sedation, hypnotic, muscle relaxation, anxiolytic, etc. Phenibut is a moderately mild-average GABA-B receptor agonist, meaning it can boost the amount of GABA released. It’s main effects come from it being like a gabapentinoid, which means it also binds to the GABA-B calcium channels and blocks them. This causes different signals to happen due to the channels being open or closed. Because of this, and because Phenibut isn’t identical to gabapentin or pregabalin (both gabapentinoids), it causes different signals to influence other neurotransmitters. It can be said that it causes a boost of dopamine as well as natural endorphins. It has a more stimulating effect at the right doses than any benzo, which is more sedating. Benzos only modulate GABA at the GABA-A receptor sites, but Phenibut can sometimes activate both GABA-B and GABA-A, giving a unique effect as well. The people who use it recreationally enjoy the body and mental high as well as the increase in sociability since a lot of people take it for social anxiety and going to parties so they can be more talkative and outgoing. Phenibut can also be used for insomnia and sleep issues. It is very effective in my experience. I have chronic insomnia and even with sleep meds I still wake up a bunch of times a night. Phenibut has allowed me to sleep thru the entire night once except I did wake up after the sun came up around 7am because I had to pee really badly. Otherwise, I went right back to sleep. I also noticed I can feel more refreshed on less sleep, which is good if you are a parent to young children who get up super early. Another use that is interesting is using it before exercise and going to the gym to work out. Phenibut can give you more endurance and enjoyment doing exercise, so you benefit more from each workout. This could be from the increased release of endorphins. This is one thing I really enjoy doing myself and have noticed really great benefits as well as it putting me in a real motivated state and mood and I feel like I could workout forever it seems! I definitely notice the difference when I go to the gym without taking it (because I am taking a break from it to lower tolerance). One thing to keep in mind is once you find the ideal therapeutic dose, you won’t get the same effects every time you take it if you use it every day. Tolerance to some of the actions like euphoria and body high tend to disappear. This is why a lot of users suggest taking it only 1–3 days a week MAXIMUM. It is possible to become dependent on Phenibut, but the withdrawal is not supposed to be as intense and life-threatening like benzos are (due to seizures, etc). A high dose is considered anything more than 2g/day. Therapeutic doses can be as low as 250–750mg/day. Considering this is a prescription medication used in Russia, it does have some psychiatric use. People taking therapeutic doses are less likely to have extreme reactions or build rapid tolerance to Phenibut. There are some people who take Phenibut from unreliable sources that claim they do not feel anything on it that is noticeable even at high doses for a first time (1g-2g). It’s just like some people do not respond to certain benzodiazepines (one seems to work the best for different people as well as what kind of dose is needed), as well as SSRIs, which all are selective serotonin reuptake inhibitors, because each one may be selective to different subtypes of serotonin (5HT) receptors, which are quite numerous, each one and its variations seem to do different things. Some people don’t respond to SSRIs at all (2/3 of people apparently according to statistics), but the rest that do respond find that they really have helped them and changed their lives by boosting their moods, etc. Are you going to feel Phenibut the first time you take it? Since it is not controlled in the USA, for example, it is sold as a “supplement” or found on “nootropic” websites. There are a lot of good vendors out there just like there are a lot of bad ones do to the supplement field being so uncontrolled compared to prescription drugs, which are controlled and regulated by the FDA & DEA to be a certain level of purity. So if you get a bad batch, you may find yourself feeling nothing. But if you get a good batch (I’ve found at least 2 that I would definitely call awesome supplement/nootropic suppliers online), you should be more inclined to feel something at least, unless you are one of those genetic exceptions that don’t benefit from this type of agonist/channel blocking. Be sure to start lower dose and if you don’t feel anything in 4 hours at least, then you could try another dose. But really don’t go overboard thinking a huge dose will be good for you. Some people report getting nauseous, overly sleepy, and having other reactions you don’t want. You don’t want to pass out and wake up having to throw up over and over. Don’t mix it with alcohol, as alcohol tends to modulate GABA in various ways as well as some other neurotransmitters and hormones. They can create a combined effect. Interestingly, some people use Phenibut to give them the same desired effects of alcohol (ability to socialize, being more talkative and clever, going out with friends to have fun at a club or whatever, etc) without the messiness of it (getting drunk, dizzy, nauseous, throwing up, headaches, sour stomach, hangovers, etc). Be sure to respect it like you would any prescription medication, since it is one in certain Countries, even if it is just a supplement in yours. Proper titration of the ideal dose as well as cycling (taking days off or even taking a break for a while from all use) are really important. These can affect the potency of Phenibut each time you use it.
  3. Dec 2022
    1. ConvertSaveload

      It would be good to describe why ConvertSaveload is used here, as well as how to configure it in Cargo.toml.

      [dependencies] changes I needed in Cargo.toml:

      serde = { version = "1.0.148", features = ["derive"]} specs = { version = "0.18.0", features = ["serde"]}

      and imports:

      ``` use serde::{Deserialize, Serialize}; use specs::{ prelude::*, saveload::{ConvertSaveload, Marker}, Entity, };

      use specs_derive::{Component, ConvertSaveload}; use std::convert::Infallible;

      // NoError alias is deprecated in specs ... but specs_derive needs it pub type NoError = Infallible; ```

  4. Nov 2022
    1. The function signature now tells Rust that for some lifetime 'a, the function takes two parameters, both of which are string slices that live at least as long as lifetime 'a. The function signature also tells Rust that the string slice returned from the function will live at least as long as lifetime 'a. In practice, it means that the lifetime of the reference returned by the longest function is the same as the smaller of the lifetimes of the values referred to by the function arguments.
    1. Copy and Clone. Clone adds a .clone() method to the type, allowing a copy to be made programmatically. Copy changes the default from moving the object on assignment to making a copy - so tile1 = tile2 leaves both values valid and not in a "moved from" state.
    2. Roguelike. [Rogue](https://en.wikipedia.org/wiki/Rogue_(video_game)

      fix hyperlink

    1. context

      should introduce the context earlier, as well as the main function's BError type.

    2. The "S" in ECS stands for "Systems". A System is a piece of code that gathers data from the entity/components list and does something with it. It's actually quite similar to an inheritance model, but in some ways it's "backwards". For example, drawing in an OOP system is often: For each BaseEntity, call that entity's Draw command. In an ECS system, it would be Get all entities with a position and a renderable component, and use that data to draw them.
    3. You can find the glyphs available here.

      Link is dead, maybe use wikipedia instead.

    4. In our tick function

      Need to introduce the tick function and GameState here.

    1. I like to say that in ECS we design bottom-up. We look at data and which behaviour depends on which data. In OO we design top-down, we search for abstractions and generic behaviours / definitions.
  5. Dec 2021
    1. ZLayer provided a very clean solution to the problems developers were havingwith ZIO Environment—not perfect, mind you, and I don’t think any solutionprior to Scala 3 can be perfect (every solution in the design space has differenttradeoffs). This solution became even better when the excellent consultancySeptimal Mind donated Izumi Reflect to the ZIO organization
    2. Has can be thought of as a type-indexed heterogeneous map, which is type safe,but requires access to compile-time type tag information. ZLayer can be thoughtof as a more powerful version of Java and Scala constructors, which can buildmultiple services in terms of their dependencies.
  6. Aug 2021
    1. We can also define these properties for data types that we do not control, for example providing a custom way of hashing a data type implemented by someone else
    1. However, there is a definite trade off in these three snippets. The first one is overly specific but is understandable to any Scala programmer. The last one is beautiful and elegant if you understand the necessary concepts but incomprehensible otherwise.
    2. ZIO ecosystem libraries generally do not directly expose any functional abstractions but still expose a highly compositional interface because their design is based on algebraic properties like this. Users don't have to learn about these abstractions unless they want to, they just get to benefit from better library design.
  7. Jul 2021
    1. The keyword data tells us this is an inductive definition, that is, that we are defining a new datatype with constructors

      Inductive, since multiple constructors are generalized to a type. And as seen in this example, data types can also facilitate mathematical induction.

  8. Jun 2021
    1. In V however, you can compile and run the whole folder of .v files together, using just v run .. Passing parameters also works, so you can do: v run . --yourparam some_other_stuff
  9. Apr 2021
    1. Inlining is a new metaprogramming feature to achieve better performance during compile time. Scala 3 introduces the inline soft keyword which guarantees inlining is executed instead of being a best-effort. This is different when using the final keyword, which is based on a best-effort. After a constant is inlined, then other constants based on the inlined constant are computed compile-time:
  10. Mar 2021
    1. Put another way, it’s become clear to me over time that the problems with data races and memory safety arise when you have both aliasing and mutability. The functional approach to solving this problem is to remove mutability. Rust’s approach would be to remove aliasing. This gives us a story to tell and helps to set us apart. A note on terminology: I think we should refer to aliasing as sharing. In the past, we’ve avoided this because of its multithreaded connotations. However, if/when we implement the data parallelism plans I have proposed, then this connotation is not at all inappropriate. In fact, given the close relationship between memory safety and data races, I actually want to promote this connotation.
  11. Feb 2021
    1. Do you like collard greens? If so, what’s your favorite way of preparing them? Please let us know in the comments.

      Great with (baby) bok choy - use a couple of bags.

    1. The most widely used form of macros in Rust is declarative macros. These are also sometimes referred to as “macros by example,” “macro_rules! macros,” or just plain “macros.” At their core, declarative macros allow you to write something similar to a Rust match expression.
    1. Following food author Michael Pollan’s simple advice about choosing a diet may be the best way forward: “Eat food. Not too much. Mainly plants.”

      Probably the best general health advice out there.

  12. Jan 2021
    1. As an example, recall the Sync and Send marker traits we discussed in the “Extensible Concurrency with the Sync and Send Traits” section in Chapter 16: the compiler implements these traits automatically if our types are composed entirely of Send and Sync types. If we implement a type that contains a type that is not Send or Sync, such as raw pointers, and we want to mark that type as Send or Sync, we must use unsafe. Rust can’t verify that our type upholds the guarantees that it can be safely sent across threads or accessed from multiple threads; therefore, we need to do those checks manually and indicate as such with unsafe.
    2. Constants and immutable static variables might seem similar, but a subtle difference is that values in a static variable have a fixed address in memory. Using the value will always access the same data. Constants, on the other hand, are allowed to duplicate their data whenever they’re used.
    3. As with references, raw pointers can be immutable or mutable and are written as *const T and *mut T, respectively. The asterisk isn’t the dereference operator; it’s part of the type name. In the context of raw pointers, immutable means that the pointer can’t be directly assigned to after being dereferenced. Different from references and smart pointers, raw pointers: Are allowed to ignore the borrowing rules by having both immutable and mutable pointers or multiple mutable pointers to the same location Aren’t guaranteed to point to valid memory Are allowed to be null Don’t implement any automatic cleanup
    1. Ignoring a function parameter can be especially useful in some cases, for example, when implementing a trait when you need a certain type signature but the function body in your implementation doesn’t need one of the parameters. The compiler will then not warn about unused function parameters, as it would if you used a name instead.
    1. The changes we needed to make to main to reassign post mean that this implementation doesn’t quite follow the object-oriented state pattern anymore: the transformations between the states are no longer encapsulated entirely within the Post implementation. However, our gain is that invalid states are now impossible because of the type system and the type checking that happens at compile time! This ensures that certain bugs, such as display of the content of an unpublished post, will be discovered before they make it to production.

      This is really an amazing chapter for comparing (some aspects) of object oriented and functional programming, and I have to admit I still prefer the functional approach as a default.

    1. You can only make object-safe traits into trait objects. Some complex rules govern all the properties that make a trait object safe, but in practice, only two rules are relevant. A trait is object safe if all the methods defined in the trait have the following properties: The return type isn’t Self. There are no generic type parameters.
    2. Trait Objects Perform Dynamic Dispatch Recall in the “Performance of Code Using Generics” section in Chapter 10 our discussion on the monomorphization process performed by the compiler when we use trait bounds on generics: the compiler generates nongeneric implementations of functions and methods for each concrete type that we use in place of a generic type parameter. The code that results from monomorphization is doing static dispatch, which is when the compiler knows what method you’re calling at compile time. This is opposed to dynamic dispatch, which is when the compiler can’t tell at compile time which method you’re calling. In dynamic dispatch cases, the compiler emits code that at runtime will figure out which method to call.
    1. To many people, polymorphism is synonymous with inheritance. But it’s actually a more general concept that refers to code that can work with data of multiple types. For inheritance, those types are generally subclasses. Rust instead uses generics to abstract over different possible types and trait bounds to impose constraints on what those types must provide. This is sometimes called bounded parametric polymorphism.
    2. For example, we can define a struct AveragedCollection that has a field containing a vector of i32 values. The struct can also have a field that contains the average of the values in the vector, meaning the average doesn’t have to be computed on demand whenever anyone needs it. In other words, AveragedCollection will cache the calculated average for us.

      This is a good example of encapsulation.

    1. The Sync marker trait indicates that it is safe for the type implementing Sync to be referenced from multiple threads. In other words, any type T is Sync if &T (a reference to T) is Send, meaning the reference can be sent safely to another thread. Similar to Send, primitive types are Sync, and types composed entirely of types that are Sync are also Sync.
    2. Any type composed entirely of Send types is automatically marked as Send as well. Almost all primitive types are Send, aside from raw pointers, which we’ll discuss in Chapter 19.
    1. As you might suspect, Mutex<T> is a smart pointer. More accurately, the call to lock returns a smart pointer called MutexGuard, wrapped in a LockResult that we handled with the call to unwrap. The MutexGuard smart pointer implements Deref to point at our inner data; the smart pointer also has a Drop implementation that releases the lock automatically when a MutexGuard goes out of scope, which happens at the end of the inner scope in Listing 16-12. As a result, we don’t risk forgetting to release the lock and blocking the mutex from being used by other threads because the lock release happens automatically.
    1. In this context, by runtime we mean code that is included by the language in every binary. This code can be large or small depending on the language, but every non-assembly language will have some amount of runtime code. For that reason, colloquially when people say a language has “no runtime,” they often mean “small runtime.”
    1. *value.borrow_mut() += 10;

      Note that . has higher precedence than *. Here it's:

      *(value.borrow_mut()) += 10
      

      not:

      (*value).borrow_mut() += 10
      
    1. Here’s how it works: when you call a method with object.something(), Rust automatically adds in &, &mut, or * so object matches the signature of the method. In other words, the following are the same:
    1. We could have called a.clone() rather than Rc::clone(&a), but Rust’s convention is to use Rc::clone in this case. The implementation of Rc::clone doesn’t make a deep copy of all the data like most types’ implementations of clone do. The call to Rc::clone only increments the reference count, which doesn’t take much time. Deep copies of data can take a lot of time. By using Rc::clone for reference counting, we can visually distinguish between the deep-copy kinds of clones and the kinds of clones that increase the reference count. When looking for performance problems in the code, we only need to consider the deep-copy clones and can disregard calls to Rc::clone
    2. We could change the definition of Cons to hold references instead, but then we would have to specify lifetime parameters. By specifying lifetime parameters, we would be specifying that every element in the list will live at least as long as the entire list. The borrow checker wouldn’t let us compile let a = Cons(10, &Nil); for example, because the temporary Nil value would be dropped before a could take a reference to it.
    1. You can use code specified in a Drop trait implementation in many ways to make cleanup convenient and safe: for instance, you could use it to create your own memory allocator! With the Drop trait and Rust’s ownership system, you don’t have to remember to clean up because Rust does it automatically.
    1. Panics: The scenarios in which the function being documented could panic. Callers of the function who don’t want their programs to panic should make sure they don’t call the function in these situations. Errors: If the function returns a Result, describing the kinds of errors that might occur and what conditions might cause those errors to be returned can be helpful to callers so they can write code to handle the different kinds of errors in different ways. Safety: If the function is unsafe to call (we discuss unsafety in Chapter 19), there should be a section explaining why the function is unsafe and covering the invariants that the function expects callers to uphold.

      The four common sections are Examples, Panics, Errors, and Safety. OF these, I'm most uncertain about Errors, as I'd have thought this would largely be taken care of by the type (signature).

  13. Dec 2020
    1. You might see suggestions to use the 'static lifetime in error messages. But before specifying 'static as the lifetime for a reference, think about whether the reference you have actually lives the entire lifetime of your program or not. You might consider whether you want it to live that long, even if it could. Most of the time, the problem results from attempting to create a dangling reference or a mismatch of the available lifetimes. In such cases, the solution is fixing those problems, not specifying the 'static lifetime.
    2. and you’ll see that the borrow checker approves of this code;

      I found this post to be helpful in understanding why lifetimes aren't automatically inferred in these cases.

    3. The first rule is that each parameter that is a reference gets its own lifetime parameter. In other words, a function with one parameter gets one lifetime parameter: fn foo<'a>(x: &'a i32); a function with two parameters gets two separate lifetime parameters: fn foo<'a, 'b>(x: &'a i32, y: &'b i32); and so on. The second rule is if there is exactly one input lifetime parameter, that lifetime is assigned to all output lifetime parameters: fn foo<'a>(x: &'a i32) -> &'a i32. The third rule is if there are multiple input lifetime parameters, but one of them is &self or &mut self because this is a method, the lifetime of self is assigned to all output lifetime parameters. This third rule makes methods much nicer to read and write because fewer symbols are necessary.
    4. Note: The examples in Listings 10-17, 10-18, and 10-24 declare variables without giving them an initial value, so the variable name exists in the outer scope. At first glance, this might appear to be in conflict with Rust’s having no null values. However, if we try to use a variable before giving it a value, we’ll get a compile-time error, which shows that Rust indeed does not allow null values.
  14. Oct 2020
    1. Multiply that number by 85 percent to roughly approximate an effort cap for easy runs (though adjusting to a different percentage if you feel like that’s a bit too hard or too easy).

      Another article suggests subtracting 20bpm

  15. Jul 2018
    1. “pulls it back”

      minor quibble, maybe this should be surrounded by parantheses

  16. Jun 2018
    1. Exercise1.75.Doesbù3chave a right adjointR:N!N? If not, why? If so, does itsright adjoint have a right adjoint?
    2. Remark1.73.IfPandQare total orders andf:P!Qand1:Q!Pare drawn witharrows bending as in Exercise 1.72, we believe thatfis left adjoint to1iff the arrows donot cross. But we have not proved this, mainly because it is difficult to state precisely,and the total order case is not particularly general
    3. x3yif and only ifdxù3e y

      Maybe x and y (at least y) should be said to be natural numbers here, but then again it is fairly obvious from the context.

    4. Writedzeforthe smallest natural number greater thanz2R, and writebzcfor the largest naturalnumber smaller thanz2R, e

      I think both of these definitions should include "or equal to", especially given the immediate following example of x <= 3y if and only if ...

    5. The preservation of meets and joins, and hence whether a monotone map sustainsgenerative effects, is tightly related to the concept of a Galois connection, or moregenerally an adjunction.
    6. Galois connections between posets were first considered by Évariste Galois—whodidn’t call them by that name—in the context of a connection he found between “fieldextensions” and “automorphism groups”. We will not discuss this further,
    7. In his work on generative effects, Adam restricts his attention to maps that preservemeets, even while they do not preserve joins. The preservation of meets implies that themapbehaves well when restricting to a subsystem, even if it can throw up surpriseswhen joining systems
    8. n [Ada17], Adam thinks of monotone maps as observations. A monotone map:P!Qis a phenomenon ofPas observed byQ. He defines generative effects of such a mapto be its failure to preserve joins (or more generally, for categories, its failure topreserve colimits)
    9. Example1.61.Consider the two-element setPfp;q;rgwith the discrete ordering.The setAfp;qgdoes not have a join inPbecause ifxwas a join, we would needpxandqx, and there is no such elementx.Example1.62.In any posetP, we havep_pp^pp.Example1.63.In a power set, the meet of a collection of subsets is their intersection,while the join is their union. This justifies the terminology.Example1.64.In a total order, the meet of a set is its infimum, while the join of a set isits supremum.Exercise1.65.Recall the division ordering onNfrom Example 1.29: we say thatnmifndivides perfectly intom. What is the meet of two numbers in this poset? Whatabout the join?

      These are all great examples. I htink 1.65 is gcd and lcm.

    10. These notions will have correlates in category theory, called limits and colimits,which we will discuss in the Chapter 3. For now, we want to make the definition ofgreatest lower bounds and least upper bounds, called meets and joins, precise.
    11. Ifxyandyx, we writexyand sayxandyareequivalent. We call a set with a preorder aposet.
    12. Example1.49.Recall from Example 1.36 that given a setXwe defineEXto be theset of partitions onX, and that a partition may be defined using a surjective functions:XPfor some setP.Any surjective functionf:X!Yinduces a monotone mapf:EY! EX, going“backwards”. It is defined by sending a partitions:YPto the compositef:s:XP
    13. s

      Not really a typo, but slightly confusing since s is also used for a different funciton in the same example in the following paragraph.

    14. Example1.42 (Opposite poset).Given a posetπP;∫, we may define the opposite posetπP;op∫to have the same set of elements, but withpopqif and only ifqp.
    15. Example1.40 (Product poset).Given posetsπP;∫andπQ;∫, we may define a posetstructure on the product setPQby settingπp;q∫  πp0;q0∫if and only ifpp0andqq0. We call this theproduct poset. This is a basic example of a more generalconstruction known as the product of categories
    16. Contrary to the definition we’ve chosen, the term poset frequently is used to meanpartiallyordered set, rather than preordered set. In category theory terminology, therequirement thatxyimpliesxyis known asskeletality. We thus call partiallyordered setsskeletal posets
  17. May 2018
  18. Aug 2017
    1. If zone reclaim is switched on, the kernel still attempts to keep the reclaim pass as lightweight as possible. By default, reclaim will be restricted to unmapped page-cache pages. The frequency of reclaim passes can be further reduced by setting /proc/sys/vm/min_unmapped_ratio to the percentage of memory that must contain unmapped pages for the system to run a reclaim pass. The default is 1 percent.

      This is a percentage of the total pages in each zone. Zone reclaim will only occur if more than this percentage of pages are in a state that zone_reclaim_mode allows to be reclaimed.

      If zone_reclaim_mode has the value 4 OR'd, then the percentage is compared against all file-backed unmapped pages including swapcache pages and tmpfs files. Otherwise, only unmapped pages backed by normal files but not tmpfs files and similar are considered.

      Source

    2. There is a knob in the kernel that determines how the situation is to be treated in /proc/sys/vm/zone_reclaim. A value of 0 means that no local reclaim should take place. A value of 1 tells the kernel that a reclaim pass should be run in order to avoid allocations from the other node. On boot- up a mode is chosen based on the largest NUMA distance in the system.

      This appears to be /proc/sys/vm/zone_reclaim_mode now.

    3. There has been some recent work in making the scheduler NUMA-aware to ensure that the pages of a process can be moved back to the local node, but that work is available only in Linux 3.8 and later, and is not considered mature.

      Stamped2 KNL nodes are already running 3.10, so this is likely available.

    4. The active memory allocation policies for all memory segments of a process (and information that shows how much memory was actually allocated from which node) can be seen by determining the process id and then looking at the contents of /proc/<pid>/numa_maps.
    5. How memory is allocated under NUMA is determined by a memory policy. Policies can be specified for memory ranges in a process's address space, or for a process or the system as a whole. Policies for a process override the system policy, and policies for a specific memory range override a process's policy.
    6. The main performance issues typically involve large structures that are accessed frequently by the threads of the application from all memory nodes and that often contain information that needs to be shared among all threads. These are best placed using interleaving so that the objects are distributed over all available nodes.
    7. In general, small Unix tools and small applications work very well with this approach. Large applications that make use of a significant percentage of total system memory and of a majority of the processors on the system will often benefit from explicit tuning or software modifications that take advantage of NUMA.
    8. The most common assumptions made by the operating system are that the application will run on the local node and that memory from the local node is to be preferred.
    9. A NUMA system classifies memory into NUMA nodes (which Solaris calls locality groups).
    10. Modern processors have multiple memory ports, and the latency of access to memory varies depending even on the position of the core on the die relative to the controller. Future generations of processors will have increasing differences in performance as more cores on chip necessitate more sophisticated caching.
    11. A memory access from one socket to memory from another has additional latency overhead to accessing local memory—it requires the traversal of the memory interconnect first.
    12. The performance differences to memory were noticeable first on large-scale systems where data paths were spanning motherboards or chassis. These systems required modified operating-system kernels with NUMA support that explicitly understood the topological properties of the system's memory (such as the chassis in which a region of memory was located) in order to avoid excessively long signal path lengths. (Altix and UV, SGI's large address space systems, are examples. The designers of these products had to modify the Linux kernel to support NUMA; in these machines, processors in multiple chassis are linked via a proprietary interconnect called NUMALINK.)
    1. Some people think that these system calls are a good way to improve the performance of a high-performance process on a system. A common use case I’ve seen in the real world is to try to call mlockall() on a program that’s supposed to running with very high performance. The reasoning is that if the program is paged out to disk, that will reduce performance; therefore mlockall() will improve things.If you try to actually use mlockall() in this way you might run into some difficulties because most systems have a very low default ulimit on the number of pages a process can lock. With some twiddling of the default ulimits you can get this working, but perhaps it’s worth considering why the default ulimits are so low in the first place.
  19. Jun 2017
    1. Vmay only extenduniversaltraitsTraits in Scala extendAnyRefby default, so value classes cannot extend them. Traitswhich explicitly extendAnyare called universal, they do not extendAnyRefand valueclasses can extend them. Like value classes and for the same reasons, universal traitsneed to be ephemeral.
    2. On line 2,xneeds to be boxed because the expected type of the expression isAnyValand primitives on the JVM do not have a common supertype.
    1. zfsembedsdatadirectlyinalogentry.Forlargeval-ues,itwritesdatatodiskredirect-on-write,andstoresapointerinthelog[21].Thisgiveszfsfastdurabilityforsmallwritesbyflushingthelog,avoidstheoverheadofwritinglargevaluestwice,andretainstherecoveryse-manticsofdatajournaling.Ontheotherhand,btrfs[26]usesindirectionforallwrites,regardlessofsize.Itwritesdatatonewly-allocatedblocks,andrecordsthosewriteswithpointersinitsjournal
  20. Mar 2017
    1. Exercise is often positioned as something that always lowers blood glucose; however, high-intensity exercise, such as sprinting or weight lifting, can sometimes raise blood glucose. This stems from the adrenaline response, which tells the body to release stored glucose. Often, I find this happens when I’m exercising in the morning on an empty stomach. But this is not a reason to avoid high intensity exercise – studies show it can improve blood glucose for one to three days post-exercise! Note that in some cases high-intensity exercise can also drop blood glucose very rapidly (2-3 mg/dl per minute), especially if you have insulin on board in your pump. The best way to see how individual exercise sessions affect your blood glucose is to test prior and after activity. “The Impact of brief, high-intensity exercise on blood glucose levels” (Diabetes Metab Syndr Obes 2013)
    1. Findings In a meta-regression analysis of 49 clinical trials with 312 175 participants, each 1-mmol/L (38.7-mg/dL) reduction in LDL-C level was associated with a relative risk (RR) of major vascular events of 0.77 (95% CI, 0.71-0.84; P < .001) for statins and 0.75 (95% CI, 0.66-0.86; P = .002) for established nonstatin interventions that act primarily via upregulation of LDL receptor expression.Meaning These data suggest statins and nonstatin therapies that act through upregulation of LDL receptor expression are associated with similar cardiovascular risk reduction per decrease in LDL-C. The clinical value of adding specific nonstatin interventions to lower LDL-C to background statin therapy should be confirmed in appropriately powered clinical trials.
    1. In addition, the vast majority of animal studies have shown that oral administration of PS reduces the progression atherosclerosis. However, it has been recently suggested that an increase in PS plasma concentrations may increase CV risk. Evidence to support this hypothesis come mainly from observations in sitosterolemic patients who hyperabsorb PS and cholesterol and display very high levels of PS, which may be associated with a premature atherosclerosis. Some epidemiological studies in non-sitosterolemic subjects have shown a positive correlation between PS plasma levels and coronary heart disease. However, these are observational studies and some of them present major methodological bias. In addition, recent studies with a larger number of subjects have indicated, either an absence or a negative relationship between PS and the incidence of CV disease.
    1. One way exercise can protect against atherosclerosis (and therefore heart disease) is by increasing shear stress on the arterial walls, which causes the endothelium to become less permeable (less accepting of oxidized LDL particles) and produce more nitric oxide (a potent inhibitor of LDL oxidation). You can think of exercise, then, not just as training for your muscles, but also for your arterial walls. It’s enough of an inflammatory stressor to induce an adaptive response. Of course, too much shear stress can be too inflammatory and might actually cause atherosclerosis to progress.
    1. The most effective approach has been minimizing fat stores located inside the abdominal cavity (visceral body fat) in addition to minimizing total body fat.[46] Visceral fat, which is more metabolically active than subcutaneous fat, has been found to produce many enzymatic signals, e.g. resistin, which increase insulin resistance and circulating VLDL particle concentrations, thus both increasing LDL particle concentrations and accelerating the development of diabetes mellitus.
    1. In summary, reducing dietary saturated fat is associated with an increase in LDL-receptor abundance of magnitude similar to the decrease in serum LDL-cholesterol. Thus, an important mechanism by which reductions in dietary saturated fatty acids decrease LDL-cholesterol in humans is through an increase in LDL-receptor number.
    1. Polyunsaturated fats protect against cardiovascular disease by providing more membrane fluidity than monounsaturated fats, but they are more vulnerable to lipid peroxidation (rancidity). The large scale KANWU study found that increasing monounsaturated fat and decreasing saturated fat intake could improve insulin sensitivity, but only when the overall fat intake of the diet was low.[1] However, some monounsaturated fatty acids (in the same way as saturated fats) may promote insulin resistance, whereas polyunsaturated fatty acids may be protective against insulin resistance.[2][3] Studies have shown that substituting dietary monounsaturated fat for saturated fat is associated with increased daily physical activity and resting energy expenditure. More physical activity was associated with a higher-oleic acid diet than one of a palmitic acid diet. From the study, it is shown that more monounsaturated fats lead to less anger and irritability.[4]
    1. In line with data in humans [8], feeding of dietary monounsaturated fat to nonhuman primates reduced LDL without lowering HDL, and in comparison to saturated and polyunsaturated fat, provided the lowest LDL to HDL ratio [9•]. On the other hand, replacement of some of the saturated fat with monounsaturated fat was associated with an even greater enrichment of LDL particles with cholesteryl oleate, a change in LDL particle composition that has been shown to confer atherogenicity [9•]. However, caution is needed in applying the results from animal experiments to humans.
  21. Aug 2016
    1. The stringSingleton() method of the Module object appears to be indistinguishable from a first-class function value. But the appearances are deceptive. The method isn’t free-standing: we could have used this in its body and it would have referred to the Module singleton object, even after the import. And it’s not the method which is passed to map — instead a transient function value is implicitly created to invoke the stringSingleton() method (this is a process known as eta-expansion) and it’s that function-value which is passed to map.
    2. Here the method subtypePolymorphic() has no type parameters, so it’s parametrically monomorphic. Nevertheless, it can be applied to values of more than one type as long as those types stand in a subtype relationship to the fixed Base type which is specified in the method signature — in other words, this method is both parametrically monomorphic and subtype polymorphic.
  22. Jul 2016
    1. Ax=b

      Apparently \(Ax = b\) is not required, but is used as a technical prop in subsequent proof construction.

      If no linear constraints are found, either A, b can be viewed as zero, or can be viewed as the smallest affine set that includes S. In both cases, this effectively makes the constraint trivial.

    2. A

      How does one go about choosing (a good) A, especially since it seems to not be necessary to have a non-trivial (A,b) pair?

    3. x()=2Feas, that is,1(x)< , establishing the claim

      So it appears that we don't need to get feasible points at each iteration?

      Answer: correct, this is pointed out later in a couple of pages, where it is stated \(x\) need not be feasible, but \(x'\) will be.

    4. int(dom(f))

      Why isn't \(x \in dom(f)\) sufficient?

      Ah, I think it is sufficient for \(t' = f(x')\), but we also need \(x \in int(dom(f))\) for the subsequently mentioned subdifferentials.

    5. (x0;t0)2bdy(dom(f))

      Confirmed that this should be \(bdy(epi(f))\), not \(bdy(dom(f))\)

    6. because(x;t) =1(x)

      Why?

    7. a value we now know to be positive and nite

      Where is the proof that if \( \alpha_1 (x) \) is infinite, then \( \alpha_2 (x,t) \) is finite?

      I now see that it starts at the beginning of page 3, but without any forward reference it seems that it is being skipped.

    8. Approximating2(x;t) is the same as approximating the solutionto() = 0,

      Not completely clear to me why this is the case.

    9. Assume eis a known feasible point contained in int(S\dom(f)).

      How to pick? Perhaps a reference to strategies, or note that strategies will be discussed later.

  23. Jun 2016
    1. A common node transform is a translation by an integer distance, most often used to lay out nodes on the stage. Such integer translations maintain the device pixel mapping so that local coordinates that are integers still map to the cracks between pixels.

      What does this mean (map to the cracks between pixels)?

    1. There are alternative ways to implement a game loop in JavaFX. A slightly longer (but more flexible) approach involves the Timeline class, which is an animation sequence consisting of a set of KeyFrame objects. To create a game loop, the Timeline should be set to repeat indefinitely, and only a single KeyFrame is required, with its Duration set to 0.016 seconds (to attain 60 cycles per second). This implementation can be found in the Example3T.java file in the GitHub repo.
  24. Apr 2016
    1. In its default configuration, the CJRS web service (either deployed as an executable jar, or a war file in a servlet container) is configured to use the SLURM JobExecutionService, and directly invokes ‘srun’, ‘sbatch’, and ‘salloc’ commands that are available on the host it is running on.A natural consequence of this is that SLURM jobs are submitted using the same user ID as owner of the CJRS web service process. For the purposes of training and demonstration, it is recommended to deploy the application so that it runs as a single, unprivileged user created specifically for the purpose of training. In theory, however, anybody who obtains the executable jar file may run it on a machine they have access to, bound to some random high port exclusive to that user, allowing it to launch SLURM jobs on their behalf via the REST API.

      This will likely not be portable to Docker due to security issues; two separate users will be needed: https://docs.docker.com/engine/security/security/#docker-daemon-attack-surface

    1. Remember that the auto keyword does not automatically specify a pointer/reference for you, you need to add that yourself.
    2. A TSet stores a collection of unique values, similar to std::set. With the AddUnique and Contains methods, TArrays can already be used as sets. However, TSet has faster implementations of these operations, at the cost of not being able to use them as UPROPERTYs like TArrays. TSets are also do not index their elements like TArrays do.
    3. Containers

      I wonder if these would be good for storing metadata with prototype support (see near the end of Prototype in Game Programming Patterns).

    4. Actor

      Should be AActor

    5. Object

      Should be UObject?

    6. UE_LOG(LogTemp, Log, TEXT("Found UObject named: %s"), *CurrentObject.GetName());

      Should be:

      UE_LOG(LogTemp, Log, TEXT("Found UObject named: %s"), *(CurrentObject->GetName()));
      
    7. Using object iterators in PIE (Play In Editor) can lead to unexpected results. Since the editor is loaded, the object iterator will return all UObjects created for your game world instance, in addition to those that are just being used by the editor. Actor iterators work in much the same way as object iterators, but only work for objects that derive from AActor. Actor iterators do not have the problem noted below, and will only return objects being used by the current game world instance.
    8. MyUObject

      Shouldn't this be UMyObject?

    9. You'll first notice the inclusion of "MyClass.generated.h". Unreal will generate all the reflection data and put it into this file. You must include this file as the last include in the header file that declares your type.
    10. To use a UStruct, you do not have to extend from any particular class, you just have mark the struct with USTRUCT() and our build tools will do the base work for you. Unlike a UObject, UStructs are not garbage collected. If you create dynamic instances of them, you must manage their lifecycle yourself. UStructs are meant to be plain old data types that have the UObject reflection support for editing within the Unreal Editor, Blueprint manipulation, serialization, networking, etc.
    11. Use inheritance when you want to customize an existing AActor or UActorComponent. Use composition when you want many different AActor types to share the functionality.

      At this high level, it almost sounds as if components are a way to implement mixins in C++, though perhaps more loosely coupled in terms of class type.

    12. UActorComponents have their own behaviors and are usually responsible for functionality that is shared across many types of AActors, e.g. providing visual meshes, particle effects, camera perspectives, and physics interactions. While AActors are often given high-level goals related to their overall roles your game, UActorComponents usually perform the individual tasks that support those higher-level objectives. Components can also be attached to other Components, or can be the root Component of an Actor. A Component can only attach to one parent Component or Actor, but it may have many child Components attached to itself. Picture a tree of Components. Child Components have location, rotation, and scaling relative to their parent Component or Actor.
    13. Unreal Engine calls the creation of an AActor at runtime spawning. Spawning an actor is a bit more complicated than creating a normal object in the game. The reason is that an AActor needs to be registered with a variety of runtime systems in order to serve all of its needs. The initial location and rotation for the actor need to be set. Physics may need to know about it. The manager responsible for telling an actor to tick needs to know. And so on. Because of this, we have a method devoted to the spawning of an actor, UWorld::SpawnActor(). Once that actor is spawned successfully, its BeginPlay() method is called, followed by Tick() the next frame.
    14. AActors have their own behaviors (specialization through inheritance), but they also act as containers for a hierarchy of UActorComponents (specialization through composition). This is done through the AActor's RootComponent member, which contains a single UActorComponent that, in turn, can contain many others. Before an AActor can be placed in a level, that AActor must contain at least a USceneComponent which contains the translation, rotation, and scale for that AActor.
      • USceneComponent inherits UActorComponent
    15. An AActor is an object that is meant to be part of the gameplay experience. AActors are either placed in a level by a designer or created at runtime via gameplay systems. All objects that can be placed into a level extend from this class. Examples include AStaticMeshActor, ACameraActor, and APointLight actors. AActor derives from UObject, so enjoys all of the standard features listed in the previous section. AActors can be explicitly destroyed via gameplay code (C++ or Blueprints) or via the standard garbage collection mechanism when the owning level is unloaded from memory. AActors are responsible for the high-level behaviors of your game's objects. AActors are also the base type that can be replicated during networking. During network replication, AActors can also distribute information for any UActorComponents owned by that AActor that require network support.
    16. Each class that derives from UObject has a singleton UClass created for it that contains all of the meta data about the class instance. UObject and UClass together are at the root of everything that a gameplay object does during its lifetime. The best way to think of the difference between a UClass and a UObject is that the UClass describes what an instance of a UObject will look like, what properties are available for serialization, networking, etc. Most gameplay development does not involve directly deriving from UObjects, but instead from AActor and UActorComponent. You do not need to know the details of how UClass/UObject works in order to write gameplay code, but it is good to know that these systems exist.
  25. Mar 2016
    1. Now that our designers can call our C++ code, let us explore one more powerful way to cross the C++/Blueprint boundary. This approach allows C++ code to call functions that are defined in Blueprints. We often use the approach to notify the designer of an event that they can respond to as they see fit.
  26. Dec 2015
    1. Lemma 2.5.1.14

      Invoke universal property of products

    2. Since ducks can both swim and fly, each duck is found twice inC, once labeled as aflyer and once labeled as a swimmer. The typesAandBare kept disjoint inC, whichjustifies the name “disjoint union.”

      The disjoint union reminds me of algebraic datatypes in functional programming languages, whereas a set-theoretic union is more like a union in CS: the union has no label associated with it, so additional computation (or errors) may arise due to a lack of ready information about elements in the union.

    3. the set of mothers arises as is the image of
    4. facts, which are simply “path equivalences” in an olog. It isthe notion of path equivalences that make category theory so powerful.Apathin an olog is a head-to-tail sequence of arrows
    5. Consider the aspectpan objectqhas››››—pa weightq. At some point in history, thiswould have been considered a valid function. Now we know that the same objectwould have a different weight on the moon than it has on earth. Thus as world-views change, we often need to add more information to our olog. Even the validityofpan object on earthqhas››››—pa weightqis questionable. However to build a modelwe need to choose a level of granularity and try to stay within it, or the whole modelevaporates into the nothingness of truth!
    6. An aspect of a thingxis a way of viewing it, a particular way in whichxcan be regardedor measured. For example, a woman can be regarded as a person; hence “being a person”is an aspect of a woman. A molecule has a molecular mass (say in daltons), so “havinga molecular mass” is an aspect of a molecule. In other words, byaspectwe simply meana function. The domainAof the functionf:A—Bis the thing we are measuring, andthe codomain is the set of possible “answers” or results of the measurement.

      Naïvely (since my understanding of type theory is naïve), this seems to mesh with the concepts of inheritance for the "is" relationships, and also with type-theory more generally for "has" relationships, since I believe we can view any object or "compound type", as defined here, as being a subtype of another type 'o' if one of its elements is of type 'o'. Though we have to be careful for functional mapping when thinking of aspects: we can't just say Int is an aspect of Pair(Int, Int), since this is ambiguous (there are two ints) --- we must denote which Int we mean.

    7. We represent eachtype as a box containing asingular indefinite noun phrase.
    8. henma1››—Af›—Bb›—nis
    9. For example ifX ta,b,c,d,e,fuandX1 tb,d,euthenX1ÑXand we turn thatinto the functionX—X1given bybfi—b,dfi—d,efi—e

      Flip the X and X' in X -> X'

    10. Data gathering is ubiquitous in science. Giant databases are currently being minedfor unknown patterns, but in fact there are many (many) known patterns that simplyhave not been catalogued. Consider the well-known case of medical records. A patient’smedical history is often known by various individual doctor-offices but quite inadequatelyshared between them. Sharing medical records often means faxing a hand-written noteor a filled-in house-created form between offices.
    11. Similarly, in science there exists substantial expertise making brilliant connectionsbetween concepts, but it is being conveyed in silos of English prose known as journalarticles. Every scientific journal article has a methods section, but it is almost impossibleto read a methods section and subsequently repeat the experiment—the English languageis inadequate to precisely and concisely convey what is being done.

      This issue of reproducible science is starting to be tackled but I do believe formal methods and abstractions would go along way to making sure we adhere these ideas. It is a bit like writing a program with global state vs a functionally defined program, but even worse, since you may forget to write down one little thing you did to the global state.

    12. As mentioned above category theory has branched out into certain areas of scienceas well. Baez and Dolan have shown its value in making sense of quantum physics, itis well established in computer science, and it has found proponents in several otherfields as well. But to my mind, we are the very beginning of its venture into scientificmethodology. Category theory was invented as a bridge and it will continue to serve inthat role.
    13. All this time, however, category theory was consistently seen by much of the mathe-matical community as ridiculously abstract. But in the 21st century it has finally cometo find healthy respect within the larger community of pure mathematics. It is the lan-guage of choice for graduate-level algebra and topology courses, and in my opinion willcontinue to establish itself as the basic framework in which mathematics is done
    14. In 1980 Joachim Lambek showed that the types and programs used in computerscience form a specific kind of category. This provided a new semantics for talking aboutprograms, allowing people to investigate how programs combine and compose to createother programs, without caring about the specifics of implementation. Eugenio Moggibrought the category theoretic notion of monads into computer science to encapsulateideas that up to that point were considered outside the realm of such theory.
    15. Bill Lawvere saw category theory as a new foundation for all mathematical thought.Mathematicians had been searching for foundations in the 19th century and were reason-ably satisfied with set theory asthe foundation. But Lawvere showed that the categoryof sets is simply a category with certain nice properties, not necessarily the center ofthe mathematical universe. He explained how whole algebraic theories can be viewedas examples of a single system. He and others went on to show that higher order logicwas beautifully captured in the setting of category theory (more specifically toposes).It is here also that Grothendieck and his school worked out major results in algebraicgeometry.

      I haven't studied toposes, but I can at least see how introductory algebraic geometry, i.e. the study of Groebner bases, relates to propositional logic.

    16. The paradigm shift brought on by Einstein’s theory of relativity brought on the real-ization that there is no single perspective from which to view the world. There is nobackground framework that we need to find; there are infinitely many different frame-works and perspectives, and the real power lies in being able to translate between them.It is in this historical context that category theory got its start.
    17. These theorems have not made theirway out into the world of science, but they are directly applicable there. Hierarchies arepartial orders, symmetries are group elements, data models are categories, agent actionsare monoid actions, local-to-global principles are sheaves, self-similarity is modeled byoperads, context can be modeled by monads.
    18. No one would dispute that vector spaces are ubiquitous.But so are hierarchies, symmetries, actions of agents on objects, data models, globalbehavior emerging as the aggregate of local behavior, self-similarity, and the effect ofmethodological context.
    19. I will use a mathematical tool calledologs, or ontology logs, to givesome structure to the kinds of ideas that are often communicated in pictures like theone on the cover. Each olog inherently offers a framework in which to record data aboutthe subject. More precisely it encompasses adatabase schema, which means a system ofinterconnected tables that are initially empty but into which data can be entered.
    20. Agreementis the good stuff in science; it’s the high fives.But it is easy to think we’re in agreement, when really we’re not. Modeling ourthoughts on heuristics and pictures may be convenient for quick travel down the road,but we’re liable to miss our turnoff at the first mile. The danger is in mistaking ourconvenient conceptualizations for what’s actually there. It is imperative that we havethe ability at any time to ground out in reality.
    1. After being awarded a doctorate (Dr. rer. nat.) for her thesis on quantum chemistry,[31] she worked as a researcher and published several papers.

      Gosh, I wonder when the United States will elect someone with an equally good analytical background.

    1. Figuring out all subclasses of a class is called Class Hierarchy Analysis, and doing static CHA in a language with dynamic code loading is equivalent to solving the Halting Problem.

      Answer to question:

      Why can't the Scala compiler give pattern matching warning for nonsealed classes/traits?

      Elaboration:

      one of the goals of Scala is separate compilation and deployment of independent modules, so the compiler simply cannot know whether or not a class is subclass in another module, because it never looks at more than one module.

      Example: ??? When I try it, it seems to work, but this may be because everything I need is already loaded in the same compilation context. A subsequent answer seems to confirm this:

      It can be done (at least for all classes known at compile time), it's just expensive. You'd completely destroy incremental compilation, because everything that contains a pattern match would effectively have to be recompiled every time any other file changed.

    1. Note for this program, the shader directories that contain glsl shaders. These are files that are loaded and compiled by the OpenGL program at runtime and therefore must exist, but need not be part of the Makefile or project.
  27. Nov 2015
    1. Somewhat surprisingly, self-compassionate people actually take more responsibility for their actions. In one study, self-compassionate people who got neutral feedback about their speaking skills were more likely to attribute it to their personality (instead of, say, a mean observer) than people with high self-esteem. Mistakes and criticism don’t threaten them as much as they do for people who have to perform well all the time.
    2. Self-esteem and self-compassion might seem like opposites, but they actually go hand in hand. Self-compassionate people tend to have higher self-esteem, and both correlate with less anxiety and depression and more happiness, optimism, and positive emotion. But the differences between the two are telling. As Neff explains it, the pursuit of self-esteem is the desire to be special or above average – and since half of us aren’t, we tend to get inflated egos and look down on other people. We may refuse to see our weaknesses and be at risk for narcissism, self-absorption, self-righteous anger, prejudice, or discrimination.
    3. Perhaps the most challenging objection to self-compassion is the idea that we need an admonishing voice in our heads to spur us toward success. And we do – just not the self-critical voice that we’re all so used to hearing. Self-criticism scares us into believing that failure is unacceptable, and self-critical people tend to be more depressed, less confident, and afraid of failure. In contrast, a self-compassionate voice would motivate us with the desire for health and well-being – and we’d be more likely to listen.
    4. Isn’t the point of life to change and improve, rather than just accept things the way they are and naively believe the future will be better? In fact, mindfulness and the other techniques discussed help put us in better touch with reality so we can see things clearly and act from there. And thanks to neuroplasticity, science has shown that we are able to change.
    5. Routine meditators also retain more brain cells, while the rest of us lose 4% of ours as we age.
    6. Mindfulness at work means noticing and examining the habits of behavior, thinking, and feeling that we’ve created. Sometimes, what appears to be a problem is only a problem because of the expectations or feelings we attach to it, not the reality itself. Healey encourages us to create some distance between ourselves and our emotions and simply observe. We can also keep an eye out for little assumptions or habits that are making us unhappy, like jumping for the phone when it rings. Finally, we can cultivate mindfulness by meditating as well as injecting it into everyday experience.
    7. More mindful partners report more sexual satisfaction. More mindful students participate more. More mindful teachers burnout less. More mindful health professionals burnout less and have more self-compassion. More mindful prisoners are less angry, hostile, and moody. More mindful people with post-traumatic stress disorder have less symptoms of trauma, intrusive thoughts, avoidance, and hyperarousal.
    8. studies show changes in gene expression after 8 hours of meditating in the lab
    9. According to set point theory, our attitude and behaviors have a bigger effect on our happiness than our external circumstances – and that’s good news for mindfulness. Mindfulness shapes our brain by increasing gray matter in areas related to attention, learning, self-awareness, self-regulation, empathy, and compassion.
    10. Mindfulness literally changes our brains, making some areas more responsive, interconnected, and dense. In particular, these are areas related to empathy (the insula); memory, emotion, and emotion regulation; and reward circuitry. In response to distressing stimuli, meditators see more activation in their prefrontal structures (for awareness) and less in their fear-driven amygdala.
    11. They have helped people reduce chronic pain, improve psoriasis, and increase their immune response to the flu shot. One study of mindfulness/compassion meditation out of Emory University showed reductions in stress markers, and even a simple long exhale (ahhhh) increases vagal tone. And – last but not least – a three-month meditation training program boosted telomerase activity, indicating longer telemores and perhaps a longer life expectancy.
    12. Kabat-Zinn says that meditation is not the goal; the point of cultivating mindfulness is to learn to live our lives like they really matter now, rather than constantly living in regret or anticipation.
    13. When our mind wanders during meditation, a group of brain areas called the “default mode network” activates. Scientists aren’t exactly sure what this network does – it may be directly involved in mind wandering or simply be carrying out brain maintenance when we aren’t thinking about anything in particular. As soon as we realize our mind is wandering during meditation, other brain regions for detecting relevant events light up. As we refocus our attention on the breath, the executive brain network takes over. Experienced meditators who repeat this process thousands of times start to show differences in the brain. They develop more connection between the self-focused part of the default mode network and brain regions for disengaging attention, which makes it easier to shut off that area of the brain when they realize their minds are wandering. Over time, meditation improves working memory, fluid intelligence, and standardized test scores.
    1. It helps to share the ideas in yourgoals and plans with other people.
    2. Can you for instance advocate for awe-eliciting green spaces inthe physical spaces you inhabit to infuse communities with a greater sense of commonhumanity and increase collective happiness?
    1. Lyubomirsky makes the simple but important point that increasing your level of happiness takes sustained effort and commitment over time, just like achieving any other important goal in life.

      Now the good news is, a lot of the activities that I think foster happiness, well-being, can become habitual over time, and so, once they become habitual, the effort decreases.

    2. Humans tend to adapt to positive changes as well as negative ones, so it makes sense that trying a variety of happiness strategies can ensure that we don’t get numb to their benefits over time.

      “Variety is not only the spice of life,” write Sheldon and Lyubomirsky in a recent book chapter, “but the spice of happiness as well.”

    3. Research has also shown that the amount of effort someone puts into increasing their happiness has a large effect on whether or not an activity works. In several studies, researchers found that people who reported that they put a lot of effort into their activities saw the greatest gains in well-being. Other methods are also used to evaluate effort, such as how many characters someone writes in his or her gratitude letters.

      At first glance this seems to contradict a prior finding that doing certain activities too often, like a gratitude journal, can actually erode the positive effects. However, I suppose their is a distinction between frequency of an activity and the quality of the activity.

      In fact, this is discussed below:

      • Duration. Happiness-increasing activities are also most effective for people who engage in them for longer periods of time, research shows. The trick, says Layous, is to make a habit of one or more positive activities without wearing yourself out.

      • Dosage. Research has found that frequency and timing impact how well certain happiness-increasing activities work. More isn’t always better: The proper dosage often depends on the activity.

      [examples ...] The findings may seem contradictory, but they underscore the importance of choosing activities that feel voluntary and not burdensome, say Layous and Lyubomirsky.

    4. a study by Stephen Schueller, published last year in the Journal of Positive Psychology, found that people assigned to a happiness activity similar to one for which they previously expressed a preference showed significantly greater increases in happiness than people assigned to an activity not based on a prior preference. This, writes Schueller, is “a model for positive psychology exercises similar to Netflix for movies or Amazon for books and other products.”
    5. Extroverts, for example, would likely benefit most from positives activities that involve socializing and being surrounded by others, whereas religious people might prefer an activity with a spiritual component.
    6. In one study, Layous and Lyubomirsky found that positive activities were effective for people who were mildly depressed, but not for people who reported already being happy or severely depressed.
    7. Findings indicate that adults get more out of positive activities than adolescents and college-aged students. That said, the college-age sample may be misleading, says Layous, because many undergrads are required to participate in studies for course credit, not by their own volition. In other words, a disproportionate number of students in these studies may lack the all-important motivation that their older counterparts have.
    8. So far, Layous and Lyubomirsky’s analysis suggests that Westerners benefit more from positive activities than other populations, including Asians. One study conducted at UC Riverside found that Anglo-Americans benefitted more from happiness-increasing activities; however, researchers did see a small trend that Asians gained more from activities directed toward benefitting others’ happiness, like writing a letter of gratitude, than activities strictly intended to benefit the self.
    9. Receiving encouragement from others also seems to maximize happiness. In one study, people who read bogus testimonials from peers saying an activity worked saw greater increases in happiness than those who did not.
    10. In one study, Lyubomirsky posted online two nearly identical requests for study participants. The only difference? One version told participants the study was meant to increase their happiness, while the other simply told them they’d take part in a cognitive exercise. After performing the same happiness-inducing activities, the people who signed up for the happiness study—the group Lyubomirsky saw as more “motivated” to become happier—gained more from the study than those who signed up for the other exercise.

      The study. This sounds very similar to the placebo effect, so I wonder if they have checked to see what effects they would find if they picked activities previously classified as neutral.

    11. posit in their theorizing about person-activity fit that perhaps people who are high in sensationseeking might choose a really varied and novel kinds of activities for boosting their ownhappiness, whereas people who are more sort of quiet or less social or less extravertedare more likely to choose these less demanding self-reflective kinds of activities.
    12. For people to benefit from a positive activity,or any self-improvement behavior for that matter, they have to effortfully engage in it,be motivated to become happier, and believe that their efforts will pay off.
    1. In one version of this experiment, if we gave participants synthetic oxytocin (in the nose, that will reach the brain in an hour), they donated to 57 percent more of the featured charities and donated 56 percent more money than participants given a placebo. Those who received oxytocin also reported more emotional transportation into the world depicted in the ad. Most importantly, these people said they were less likely to engage in the dangerous behaviors shown in the ads. So, go see a movie and laugh and cry. It’s good for your brain, and just might motivate you to make positive changes in your life and in others’ lives as well.
    2. Once a story has sustained our attention long enough, we may begin to emotionally resonate with story’s characters. Narratologists call this “transportation,” and you experience this when your palms sweat as James Bond trades blows with a villain on top of a speeding train.
    3. Any Hollywood writer will tell you that attention is a scarce resource. Movies, TV shows, and books always include “hooks” that make you turn the page, stay on the channel through the commercial, or keep you in a theater seat. Scientists liken attention to a spotlight. We are only able to shine it on a narrow area. If that area seems less interesting than some other area, our attention wanders.
    4. This evidence supports the view of some narrative theorists that there is a universal story structure. These scholars claim every engaging story has this structure, called the dramatic arc. It starts with something new and surprising, and increases tension with difficulties that the characters must overcome, often because of some failure or crisis in their past, and then leads to a climax where the characters must look deep inside themselves to overcome the looming crisis, and once this transformation occurs, the story resolves itself. 
    5. When people watch Ben’s story in the lab—and they both maintain attention to the story and release oxytocin—nearly all of these individuals donate a portion of their earnings from the experiment. They do this even though they don’t have to. This is surprising since this payment is to compensate them for an hour of their time and two needle sticks in their arms to obtain blood from which we measure chemical changes that come from their brains. 

      (Ben's story is a very sad story)

    6. I recall that Martin Seligman also mentions this buffering effect in a slightly more rich context, but the essential message is the same.

    7. narratingdifficulties, frustration, stresses in the simple writing expressive paradigm leads toincreased happiness, reduced stress, reduced visits to health centers, reduced depression,even sort of better profiles of your immune system as you're handling disease.
    8. When we adults unite play, love, and work in our lives, we set an example that our children can follow. That just might be the best way to bring play back into the lives of our children—and build a more playful culture.
    9. Finally children do as we do, not as we say. That gives us incentive to bring play back into our adult lives. We can shut off the TVs and take our children with us on outdoor adventures. We should get less exercise in the gym and more on hiking trails and basketball courts. We can also make work more playful: Businesses that do this are among the most successful. Seattle’s Pike Fish Market is a case in point. Workers throw fish to one another, engage the customers in repartee, and appear to have a grand time. Some companies, such as Google, have made play an important part of their corporate culture. Study after study has shown that when workers enjoy what they do and are well-rewarded and recognized for their contributions, they like and respect their employers and produce higher quality work. For example, when the Rohm and Hass Chemical company in Kentucky reorganized its workplace into self- regulating and self-rewarding teams, one study found that worker grievances and turnover declined, while plant safety and productivity improved.
    10. As adults have increasingly thwarted self-initiated play and games, we have lost important ma