thread_id
stringlengths
6
6
question
stringlengths
1
16.3k
comment
stringlengths
1
6.76k
upvote_ratio
float64
30
396k
sub
stringclasses
19 values
ulcg1r
What was the harshest you punished your kids and why?
I spanked my 3 yo son for running out in the street between two parked cars. Only spanking he ever got. Never forgot the lesson either.
40
AskOldPeople
uldard
Where was the Hawaiian islands/hotspot located in the Mesozoic? I believe that the current islands didn’t exist until the Cenozoic, and that the oldest of the Emperor Seamounts existed during the Cretaceous period, but I have no idea where the hotspot was located or when it was created. Also, I’m wondering what climate the islands were.
Generally, when [mantle plumes](https://en.wikipedia.org/wiki/Mantle_plume) (hotspots) first reach the surface, the arrival of the plume head is accompanied by the formation of a [large igneous province](https://en.wikipedia.org/wiki/Large_igneous_province) or LIP. When a LIP erupts through oceanic lithosphere, it typically produces an [oceanic plateau](https://en.wikipedia.org/wiki/Oceanic_plateau), whereas when it erupts through continental lithosphere, it can produce continental flood basalts, like the [Deccan Traps](https://en.wikipedia.org/wiki/Deccan_Traps) or the [Columbia River Basalts](https://en.wikipedia.org/wiki/Columbia_River_Basalt_Group). For some plumes, we can trace them back along the characteristic "hotspot track" to where the plume first erupted, this is the case for both the [Reunion Hotspot](https://en.wikipedia.org/wiki/R%C3%A9union_hotspot) and [Yellowstone Hotspot](https://en.wikipedia.org/wiki/Yellowstone_hotspot), where the Deccan Traps and Columbia River Basalts represent the LIPs associated with the initial arrival of the plume head at the surface and there are "tracks" of volcanism between these LIPs and the modern plume location. In the case of the [Hawaii-Emperor](https://en.wikipedia.org/wiki/Hawaiian%E2%80%93Emperor_seamount_chain) chain and associated hotpsot, if we follow the track back, we don't find a LIP, but instead find that the chain terminates into the corner between the Kamchatka and Aleutian subduction zones. This implies that the LIP that would mark the initiation of the Hawaii-Emperor seamount chain was subducted. The oldest remaining portions of the chain (that are about to enter the Kamchatka trench) are ~81 million years old (so not that far back into the [Mesozoic](https://en.wikipedia.org/wiki/Mesozoic). The best constraint we have on how much of the chain we've lost to subduction and when the plume initiated comes from mantle tomography, where we use changes in the speed of seismic waves from earthquakes as they pass through material of different densities/temperatures to produce "images" of the mantle, kind of like a giant ultrasound. Specifically, [Wei et al., 2020](https://www.science.org/doi/full/10.1126/science.abd0312) used mantle tomography to potentially identify the subducted oceanic plateau that would mark the arrival of the Hawaii-Emperor plume head at the surface. From this, they back out that the oceanic plateau was probably subducted beneath Kamchatka about 20-30 million years ago and that the plateau itself formed 100 million years ago on the Pacific plate (so again, not terribly far back into the Mesozoic all things considered). As to where this oceanic plateau was located when it formed, largely in the same location as the modern plume is today in terms of latitude-longitude / distance from the poles. In general, hotspots are approximately fixed with respect to the rotational axes of the Earth (in detail, they're not truly fixed and they do "drift" a bit, e.g., see this [FAQ](https://www.reddit.com/r/askscience/wiki/planetary_sciences/hawaii_seamount_bend) entry considering how drift of Hawaii-Emperor seamount plume may factor into the prominent bend in the chain, but for our purposes, we can consider them close enough to being fixed to say that the plume was basically in the same place when it formed as today). The plates have moved with respect to this (and other) hotspots since their formation, so in the simplest sense, hotspot tracks mostly reflect plate motion, not motion of the hotspot (kind of like moving a piece of paper above the tip of a candle, burning a track into it). Thus, if we could go back in time to 100 Ma to watch the formation of the Hawaii-Emperor oceanic plateau (that's now hanging out at about ~850 km down in the mantle underneath Kamchatka), it would be at the approximately the same latitude and longitude as the modern big island of Hawaii, at least likely within a few degrees. If we could stay hovering above this exact spot for the next 100 million years, we would watch motion of the Pacific plate advect older seamounts and volcanoes away from the plume location and toward the Kamchatka trench, until the plateau and additional portions of the seamount chain started to be subducted.
6,230
AskScience
ulga33
My parents bought me the new M1 air (16RAM/512GB). Could it handle projects (like UNITY) and some 3D rendering. Maybe some video and music editing too. I'm currently a freshman.
No, you’ll spill some soda innit or have it stolen from your backpack while in the library.
220
AskComputerScience
ulga33
My parents bought me the new M1 air (16RAM/512GB). Could it handle projects (like UNITY) and some 3D rendering. Maybe some video and music editing too. I'm currently a freshman.
Not really the right subreddit, but almost certainly. 16Gb of RAM might be a little limiting towards the end of your schooling but generally you should be able to get 5-6 years out of it.
40
AskComputerScience
uljuvj
How does our heart produce its electric current?
Via the [sinus node](https://en.m.wikipedia.org/wiki/Sinoatrial_node) but the rate is controlled via the [medulla](https://en.m.wikipedia.org/wiki/Heart_rate). Interesting side note, the "heartbeat" in the 6-week abortion heartbeat bill is actually the embryonic SA node producing an electric pulse. The proper heart isn't fully formed until 10-12 weeks, doesn't start relieving placental circulatory resistance until 16 weeks and is difficult to monitor for developmental issues until around 20 weeks.
250
AskScience
uljuvj
How does our heart produce its electric current?
There are a series of active pumps, the most important one being the Na-K-ATPase pump as well as a series of ion channels. The electricity is caused by flow of ions through the various channels which can fluctuate between open and closed states.
170
AskScience
uljuvj
How does our heart produce its electric current?
The cells that make up the sinoatrial node are pretty cool. They have channels that produce what is called the "Funny Current" which was named that because researchers observing it could not figure out what it was at first and its behavior was pretty odd (or "funny"). Cells use the gradients of ions (Calcium, Sodium, Potassium, Chloride) across their membranes to generate currents, and trigger action potentials. In the case of the Sinoatrial (SA) node which controls the initiation of the heartbeat, the cycle of the action potential is an increase in cytoplasmic calcium that reaches a threshold, and triggers an action potential, this then triggers voltage gated potassium channels to bring the potential back down (hyperpolarize). Normally that cycle is the end of the story until some external stimuli triggers another action potential. In the SA node however, there is the funny current. HCN ion channels responsible for creating the funny current, will spontaneously open when the cell gets hyperpolarized by the potassium currents, and allow for sodium to flow into the cell. This depolarized the cells enough to trigger the calcium channels which initiate the next action potential.
80
AskScience
uljygg
Do our bodies have defences against prions?
TL:DR Prions are a normal part healthy cells. They are not something the body needs to protect against, in most cases. Prions, in very rare cases (very rare) , can become misshapen and cause problems. Prion diseases, also known as transmissible spongiform encephalopathies or TSEs, are a group of rare, fatal brain diseases that affect animals and humans.  They are caused by an infectious agent known as a prion, which is derived from a misfolded version of a normal host protein known as prion protein. Prion diseases include bovine spongiform encephalopathy (BSE or "mad cow" disease) in cattle, Creutzfeldt-Jakob disease (CJD) and variant CJD in humans, scrapie in sheep, and chronic wasting disease (CWD) in deer, elk, moose and reindeer.  Prion diseases are associated with the prion protein, which is found in many body tissues, including the brain. Normally, prion protein does not cause disease and resides on the surface of many cell types. Though under investigation, scientists think normal prion protein might help protect the brain from damage. They do know that when many normal prion protein molecules change their shape and clump together, they can aggregate in brain tissue and form the infectious prions that cause prion disease. Prion diseases are therefore caused by an infectious, abnormally shaped and aggregated prion protein. Scientists are not sure why normal prion protein become misshapen. NIAID scientists co-discovered the prion protein gene and were among the first to show that abnormal prion protein can change normal prion protein to the abnormal, infectious form. Source, NIAID research, a part of the NIH
1,120
AskScience
uljygg
Do our bodies have defences against prions?
Yes! Your body does have defenses against prions. Before we get into it, we should define some terms since it can get confusing talking about prions, prion proteins, and prion diseases. [Prion](https://en.wikipedia.org/wiki/Prion)\- a class of misfolded proteins that induce normally folded proteins to misfold. Importantly they are self-replicating (induce normal proteins and misfold) and are infectious (may be spread from one organism to another). As a class of proteins, the term prions refers to multiple proteins. [Prion protein](https://en.wikipedia.org/wiki/PRNP) (PrP) - a specific protein that may become a prion if it misfolds. PrP is the only known prion in humans and is the cause for Creutzfeldt Jakob disease (CJD, some variants known as Mad Cow Disease or transmissible spongiform encephalopathy). There are other proteins that are considered prions but most of the known ones are [yeast proteins](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2376760/). So PrP is normally found in humans and has a role in normal cell function. But when it misfolds (either due to a genetic mutation or from being exposed to a misfolded PrP from another diseased individual) it can cause disease (CJD). **The cells' defense:** Cells have an extensive system in place to protect against misfolded proteins. While not all misfolded proteins are prions, they do have a tendency to aggregate and cause dysfunction. This is evident from the multitude of protein aggregation disorders found in humans both in the brain (CJD, Alzheimer's, Parkinson's, Huntington's, ALS, etc) and in the rest of the body (amyloidosis, inclusion body myopathy, Paget's disease of the bone, etc). If your cell detects an accumulation of misfolded proteins (prions or others), it activates the unfolded protein response (UPR). This is an intricate system designed with multiple layers designed to try and fix misfolded proteins, degrade them if they are unable to be fixed, or kill off the cell if its unable to degrade misfolded proteins. It's very complex so I'll briefly describe some steps here but I'll link an excellent review below that goes into the nitty gritty. Essentially, your cells detect misfolded proteins and upregulate chaperone proteins which help guide proteins to be properly folded. If these chaperones are unable to properly folded the misfolded proteins, the misfolded proteins will be tagged for degradation with ubiquitin (a small protein used for signaling). Generally this is done by the proteasome which cleaves proteins in small pieces which can be recycled. However, larger aggregates of misfolded proteins may be degraded via autophagy which engulfs the aggregate in a compartment and then dissolves it in acid (fusion with a lysosome). If there is sustained and continued stress that is unable to be resolved by chaperones, the proteasome, or autophagy, then the cell begins programmed cell death known as apoptosis. Eventually the cell will break down resident immune cells (generally macrophages but may be others) will come by and clean up the mess. **How prions evade this defense:** Proteins misfold all the time during normal cell function. As with any manufacturing plant, there will be some defects in the products. The UPR is constantly at work in all your cells and does a great job at preventing accumulation of misfolded proteins. So how do prions or other proteins that aggregate in disease escape this mechanism? When these aggregation prone proteins misfold, they form ultra-stable conformations known as stacked beta sheets (though there are other conformations as well). These beta sheets are incredibly hydrophobic and are very resistant to degradation. So aggregation prone proteins will go from cell to cell inducing normally folded proteins to misfold, become ultra stable, and when the cell cannot degrade them, it will undergo apoptosis. It's important to note that this is not a black and white scenario as your cells are able to clear prions but when they begin to build up over time it becomes unmanageable. This is, in part, why prion disease and nearly all neurodegenerative diseases occur in the elderly. EDIT: this series of events is also why terminally differentiated cells (cells unable to divide such as neurons, myocytes, and osteocytes) are particularly vulnerable to protein aggregation. Actively dividing cells can undergo asymmetric mitosis where one daughter cell gets the bulk of the aggregates and the other remains healthy. Thus making tissues with actively dividing cells more resilient to protein aggregation including prions. [Unfolded protein response overview](https://www.nature.com/articles/nrm3270) [Prion disease and the unfolded protein response](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2838391/)
300
AskScience
uljygg
Do our bodies have defences against prions?
Not really. Most prion diseases are caused by misfolding of a specific protein. In its normal form, it's called PrPc, and it's found on the surface of healthy, normal neurons in the brain and spinal cord. As of now, we're not specifically sure what it does. What's interesting about PrPc is that it has a tendency to misfold into a form we call PrPsc. Simplified, the bad form (PrPsc) bumps into the good form (PrPc) and unfolds it using hydrogen bonds. Then, it refolds and clumps together. This creates a collection of bad proteins that ends up killing the neurons through a still unclear process. The immune system, when faced with a problem, reacts in two main ways. It has the troops on the ground (innate immunity) that react to the signals put out by bacteria, parasites, and viruses. This is blind immunity: those cells don't know what they're fighting and can go full scorched earth. This is what causes initial inflammation. The body also has the specialized troops (adaptive immunity) that release special antibodies tailored to whatever bad things it's fighting. In the case of cancer, the body has built-in mechanisms to signal "This cell is broken! Its DNA is damaged and it's dividing wrong, so kill it!" In the case of prions, none of these mechanisms are triggered. There isn't a pathogen that the immune system is recognizing, nor is there a "take care of me, I'm broken" signal. Our bodies' protective mechanism aren't triggered with prion diseases because it's just a surface protein that changes. Meanwhile, the prion works its way across the brain, misfolding and causing cell death. Because neurons in the brain have a miniscule potential to regenerate, you thus get the brain damage and signature death from prion diseases. The reason I say "not really" instead of "no" is that there's new research suggesting that microglia (defensive macrophages/ground troops of the brain) may have a protective effect against prions by clearing up the plaques and misfolded proteins. However, there's other research that suggests that microglia are actually "misfiring" during prion diseases and make things worse. Like with many parts of the brain, there's still a lot we don't know. Sources: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC1986710/#__ffn_sectitle https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5874746/ https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5750587/ https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2258253/?report=reader https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2672014/#:~:text=Prion%20diseases%20are%20fatal%20disorders,(PrP)%3B%20and%20(5) https://pubmed.ncbi.nlm.nih.gov/29769333/ https://pubmed.ncbi.nlm.nih.gov/30650564/
90
AskScience
ull014
When 9/11 happened, did any of you think it suspicious at the time? Any of you witness it in person? Do you believe it to have been a conspiracy?
I don't think it was a conspiracy. Never did. It opened the door to some really dark shit, though.
260
AskOldPeople
ull014
When 9/11 happened, did any of you think it suspicious at the time? Any of you witness it in person? Do you believe it to have been a conspiracy?
When the second tower hit, yes, I was suspicious that the first one wasn’t a freak accident. Later, I learned that it was indeed a conspiracy among operatives of an extremist group called al Qaeda.
210
AskOldPeople
ull014
When 9/11 happened, did any of you think it suspicious at the time? Any of you witness it in person? Do you believe it to have been a conspiracy?
"Do you believe it to have been a conspiracy" hell yes. I also belive Jewish Space Lasers started wildfires. microwaves turn into cameras' and can spy on us bill gates is trying to microchip us all. covid is fake. the bowling green massacare coud have been prevented. and many more very provable things normal people dismiss. Just kidding. I am not insane nor stupid.
150
AskOldPeople
ullk4w
Hey y’all. Just got a flu jab. Should I rest and deal with side effects or head out for an hour long walk? I have read that exercising after a flu shot can give a better immune boost. But I want the least side effects possible. So would a better immune response equal more side effects? I hope this makes sense. Please direct to the right sub if not the right place to ask. Thanks
The CDC recommends exercising to reduce side effects: >To reduce pain and discomfort where the shot is given > * Apply a clean, cool, wet washcloth over the area. > * Use or exercise your arm. --[Possible Side Effects After Getting a COVID-19 Vaccine](https://www.cdc.gov/coronavirus/2019-ncov/vaccines/expect/after.html) More generally, exercise helps immunity without increasing side effects: > An unconventional behavioral “adjuvant” is physical exercise at the time of vaccination. … The results show that 90 min of exercise consistently increased serum antibody to each vaccine four weeks post-immunization, and IFNα may partially contribute to the exercise-related benefit. … These findings suggest that adults who exercise regularly may increase antibody response to influenza or COVID-19 vaccine by performing a single session of light- to moderate-intensity exercise post-immunization. —[Exercise after influenza or COVID-19 vaccination increases serum antibody without an increase in side effects](https://www.sciencedirect.com/science/article/pii/S0889159122000319)
190
AskScience
ulmd2m
I want to make a sudoku game for a computer competition with a national phasea and my teacher recommended me to do it graphically. What should i use? (i only know c++ at the moment)
I highly recommend you to check out the [OneLoneCoder Pixel Engine](https://github.com/OneLoneCoder/olcPixelGameEngine) It is a very nice graphics library to create games and it is just an .hpp file.
240
cpp_questions
ulmd2m
I want to make a sudoku game for a computer competition with a national phasea and my teacher recommended me to do it graphically. What should i use? (i only know c++ at the moment)
I would recommend SFML or SDL2. Raylib is also a solid choice, but I haven't used it personally.
190
cpp_questions
ulmd2m
I want to make a sudoku game for a computer competition with a national phasea and my teacher recommended me to do it graphically. What should i use? (i only know c++ at the moment)
I’d say SDL2 as it can be used for many game related things and has tons of online help
60
cpp_questions
ulnkiy
Was it common for healthcare professionals, undertakers, etc to catch influenza from handling bodies in the 1918 Flu epidemic?
I was not able to find extremely specific information, but I cobbled some things up. The short answer is that influenza doesn't survive well in dead bodies so the risk of getting it from a body is small. I found this guideline for body handlers in Australia that specifically mentions that there is basically no risk of catching the virus from a dead body who reached the mortuary or funeral home and that the risk is mostly from the family of the victim. https://www.health.nsw.gov.au/environment/factsheets/Pages/bodies-influenza.aspx While there is a small chance for a medical professional who deals with the very recently deceased to contact the disease from him, this didn't really happen during the height of the 1918 Flu Epidemic as the whole world was overrun with bodies. I've found this chilling article explaining how bodies were put in piles on the edges of the city or kept inside the home with ice on them to prevent decomposition. Basically, by the time someone was able to get to the body, the risk of getting infected was not present. https://www.history.com/.amp/news/spanish-flu-pandemic-dead
4,870
AskScience
ulnkiy
Was it common for healthcare professionals, undertakers, etc to catch influenza from handling bodies in the 1918 Flu epidemic?
Nurses definitely got it. One of the things that slowed down the response to the pandemic in 1918 was the fact that the people who were working hardest on treatment and trying to develop vaccines kept getting sick As for handling the dead, probably not, as a respiratory virus it's just not that dangerous when the patient isn't breathing.
760
AskScience
ulnkiy
Was it common for healthcare professionals, undertakers, etc to catch influenza from handling bodies in the 1918 Flu epidemic?
"During the fall and winter months of 1918, mortality rates among physicians and nurses presumed to have influenza were 0.64% and 0.53%, respectively." https://www.centerforhealthsecurity.org/cbn/2011/cbnreport_02042011.html
390
AskScience
ulnvy4
The mullet, the crazy hairspray hair, it felt like everyone thought the bigger their hair was, the better. I always thought men were hotter when they had short hair. I didn't care for Kevin Costner until he got short hair for THE BODYGUARD and in that movie, it was hubba hubba. Before when he had the mullet, he looked like Billie Jean King. And thank god women stopped putting hairspray. Nothing ages you more than helmet hair or that hairspray hair that makes you look like you have a crown.
Twenty years from now you're going to cringe when you see photos of the hairstyle you have now.
170
AskOldPeople
ulnvy4
The mullet, the crazy hairspray hair, it felt like everyone thought the bigger their hair was, the better. I always thought men were hotter when they had short hair. I didn't care for Kevin Costner until he got short hair for THE BODYGUARD and in that movie, it was hubba hubba. Before when he had the mullet, he looked like Billie Jean King. And thank god women stopped putting hairspray. Nothing ages you more than helmet hair or that hairspray hair that makes you look like you have a crown.
The man bun is the mullet of the current era. It will be mocked in the future.
100
AskOldPeople
ulnvy4
The mullet, the crazy hairspray hair, it felt like everyone thought the bigger their hair was, the better. I always thought men were hotter when they had short hair. I didn't care for Kevin Costner until he got short hair for THE BODYGUARD and in that movie, it was hubba hubba. Before when he had the mullet, he looked like Billie Jean King. And thank god women stopped putting hairspray. Nothing ages you more than helmet hair or that hairspray hair that makes you look like you have a crown.
Every generation manages to come up with styles that the succeeding generations think look stupid. The 80s were no exception.
70
AskOldPeople
ulpzod
During Polymerase Chain Reaction, Why does Taq polymerase only extend the primer-DNA hybrid upto 1.5 kilo base pairs and not beyond that?
Processivity has to do with the likelihood of the polymerase falling off the DNA. In cells there is a protein called the clamp which literally clamps around the DNA and anchors the polymerase to the DNA. This increases processivity enormously. Its not included in the PCR design because its an extra step that is hard to control by temperature alone and requires ATP to reload the clamp every time. For most gene lengths it turns out to not be necessary in a PCR.
250
AskScience
ulqhld
Some of my team members argue that we should not use anything from the standard library or the standard template library, anything that starts with "std ::", as it may use dynamic memory allocation and we are prohibited to use that (embedded application). I argue that it is crazy to try to write copies of standard functions and you can always see which functions would need dynamic memory. Please help me with some arguments. (Happy for my opinion but if you can change my mind I will gladly accept it.)
That wording is already way too broad. Are you going to write your own `std::cos` function? I doubt it. Not to mention the few places where the core language is inseperably connected with parts of `std::`. You can find out what parts of the standard "may" allocate memory. For example `std::find` wont allocate memory, and `std::move` (both the utility as well as the algorithm) certainly wont. Sure, the string and containers (apart from `std::array`) will allocate memory - but that is their entire point. Further, you could provide a custom alloctor if you need to. Banning "all of std::" is nonsensical. Go write assembly if you want.
790
cpp_questions
ulqhld
Some of my team members argue that we should not use anything from the standard library or the standard template library, anything that starts with "std ::", as it may use dynamic memory allocation and we are prohibited to use that (embedded application). I argue that it is crazy to try to write copies of standard functions and you can always see which functions would need dynamic memory. Please help me with some arguments. (Happy for my opinion but if you can change my mind I will gladly accept it.)
I would say, "What do you mean by 'may'? Like, maybe on a whim, because it's a Monday, that today's the day this function decides to allocate?" Like, what's this "may" shit? You either know what you're talking about, or you don't know what you're talking about. Does a given thing allocate or not? And if so, how? It may blow your colleagues minds but you actually get a lot of control over such things in the STL because they tend to delegate important things to traits and policies. Your colleagues need to read a little, as it might save you all a shitload of work. Then again, writing your own dodgy stl-like library is not actually working on the real problem, which some people like to do, and it lends to job security because it's going to be such a pile of shit you guys would be at a loss to lose any of the original implementors. You see this project sabotage often in the industry. I am aware the STL isn't always available on an embedded platform, and that may be how you guys end up. I'm merely making the case that their arguments are lazy, if not dismissively ignorant. They want to sound like they know what they're talking about when it actually sounds like they don't. But if you have a whole team trying to agree with one another over this, it sounds like no one is really interested in the truth.
320
cpp_questions
ulqhld
Some of my team members argue that we should not use anything from the standard library or the standard template library, anything that starts with "std ::", as it may use dynamic memory allocation and we are prohibited to use that (embedded application). I argue that it is crazy to try to write copies of standard functions and you can always see which functions would need dynamic memory. Please help me with some arguments. (Happy for my opinion but if you can change my mind I will gladly accept it.)
Writing your own implementation of something because you can't be bothered to look up whether it does dynamic memory allocation is clearly insane. If you don't have dynamic memory allocation, it should be pretty instantly obvious when you try to use something that needs it and it fails to work properly. std explicitly has stuff like std::array for situations where std::vector is inappropriate.
300
cpp_questions
ulqwij
I'm working on legacy code that has the following three constructors: // Constructor 1 ICLoggerFile( const QString& filename = QString(), ICLoggerModel::ICLoggerModelLogLevel level = ICLoggerModel::eICLoggerModelErrorLevel, quint32 maxsize = 0, quint32 backupfiles = 0, bool append = true ); // Constructor 2 ICLoggerFile( FILE* file, ICLoggerModel::ICLoggerModelLogLevel level = ICLoggerModel::eICLoggerModelErrorLevel, const QString& filename = QString() ); // Constructor 3 ICLoggerFile( void* hnd, ICLoggerModel::ICLoggerModelLogLevel level = ICLoggerModel::eICLoggerModelErrorLevel, const QString& filename = QString() ); Inside one of our unit tests, we create an object of the `ICLoggerFile` class as follows: ICLoggerFile logfile("fooBar.log"); We are using a 64-bit build (VS2019). The strange thing is that on my local machine, the \*first\* constructor is called (as I would expect), but on our Jenkins build server, the \*third\* constructor is called, which is not what we want. My educated guess is that `"fooBar.log"` is of type `const char*`, and for some reason on my local machine this string gets implicitly converted to a `const QString&` and the first constructor is called, while on our Jenkins build server, this does not happen and the third constructor is called. My questions are: 1. Is my reasoning correct? 2. Why does this work on my own laptop, but not on our Jenkins build server? Does this code have undefined behavior or a bug in it somewhere? 3. How to refactor this code in two ways: 1. With as few changes as possible to make the problem go away, but maybe a bit less 'clean'. 2. With all the required changes to make the problem go away, and have a 'clean' solution.
Picking the 3^rd is wrong since a pointer to const something is not convertible to a pointer to non-const void. If your local and CI builds are using the same compiler, then they must be using different switches. MSVC used to be lax about string conversions, so I guess you have some permissive switch set. Edit : yes, there you go : https://godbolt.org/z/G89qd3qfv
50
cpp_questions
ulrgn5
So my thought is simple, If you see clearer at a further distance vs avg population, then your brain in turn has to process more data. Over the growth of a child, I have to imagine that much keener sight would cause a noticeable difference in ability to process information as you have to always process more. Any input on this curiosity?
>If you see clearer at a further distance vs avg population, then your brain in turn has to process more data. That matches intuition, but it ends up not being how neurovisual brain activity works. It's easy to think of ourselves as computers processing pixels in a classical computing loop (more pixels mean more processing, duh!) but we're not classical computing devices. Lower-quality input signal can actually *increase* processing overhead in neural network processing, as more resolution of ambiguity, more interpolation, and more use of higher-order reanalysis is needed to check things. You can observe this in people when you see someone who's visually challenged squint for a very long time to read something they might read quickly with correction or an easier task. They aren't generally collecting a bunch more raw visual data, but rather *thinking really hard*, in a specific way, to resolve poor signal. I'm approaching this from a computing background but I'd strongly suspect substantiation if we looked at something like fMRIs during increasingly difficult visual challenges — whether by different baseline acuity or just harder tasks, people's brains likely work a lot harder when things get blurrier. That said, what gets particularly interesting is looking at neurological *development* in early life. The brain absolutely optimizes around signal received during a "critical period" and this leads to things uncorrected astigmatism and amblyopia creating neurologically ingrained visual deficits — and potentially downstream deficits to other modes, though that gets increasingly more speculative. https://pubmed.ncbi.nlm.nih.gov/29929004/
60
AskScience
ulsdsi
I'm working on a compiler for one of the courses I need for my degree and I need to modify a major part of it (the expression evaluator) to handle optional references (I could just overload the entire thing but I don't want to duplicate code and create more work for myself). I came across `std::reference_wrapper` (and its helper functions, `std::ref` and `std::cref`). My question is: is it legal and okay to create an `std::optional<std::reference_wrapper<T>>` as a function parameter (since an `std::optional<T&>` is illegal)? If I, say, have an `std::optional<std::reference_wrapper<std::stringstream>>` and I want to write data to it and have that data remain when I return to the caller, would it be fine to use that (`std::optional<std::reference_wrapper<std::stringstream>>`) when declaring the function, or is this bad practice? Is there some better way I can use (while trying to avoid pointers)?
That is fine and what `reference_wrapper` is intended for. But let me suggest an alternative: A raw pointer. It is an indirection and it can be null. Problem sovled.
40
cpp_questions
ulskr9
Well , the question is in the title , I've found **a lot** more websites that offer c++ courses/tutorials for starters than for C But from my humble understanding : C is more simple than cpp and I may make some software for my Ubuntu pc with C Anyway, probably learning cpp is better, but the question still stands...
> Is it worth to learn C before cpp ? No. It is akin to learning latin before you learn italian. There is nothing that you would learn in C that you cannot (and wont) learn in C++ (apart from the appriciation of C++'s features). At the same time, a lot of regular C would be pretty bad if not illegal C++. In fact, by learning the "simpler" language first, you additionally burden yourself with doing a lot of stuff manually, that would take no effort in C++. --- #www.learncpp.com is the best free tutorial out there. It covers everything from the absolute basics to advanced topics. It follows modern and best practice guidelines. --- Generic resource macro below: --- #www.cppreference.com is the best language reference out there. --- Stay away from cplusplus.com ([reason](https://www.reddit.com/r/cpp_questions/comments/hjdaox/is_cpluspluscom_reliable_are_there_any/fwljj4w/)), w3schools ([reason](https://www.reddit.com/r/cpp_questions/comments/slvj8m/best_way_to_learn_c/hwczl34/)), geeks-for-geeks ([reason](https://www.reddit.com/r/cpp_questions/comments/p6305k/ways_to_learn_cpp/h9axoo7/)) and educba.com ([reason](https://www.reddit.com/r/cpp_questions/comments/rz5fkl/why_do_functions_pertaining_to_strings_on_visual/hrt7ez8/)) Most youtube tutorials are of low quality, I would recommend to stay away from them as well. A notable exception are the [CppCon Back to Basics](https://www.youtube.com/user/CppCon/search?query=back%20to%20basics) videos. They are good, topic oriented and in depth explanations. However, they assume that you have *some* knowledge languages basic features and syntax and as such arent a good entry point into the language. As a tutorial www.learncpp.com is just better than any other resource.
310
cpp_questions
ulskr9
Well , the question is in the title , I've found **a lot** more websites that offer c++ courses/tutorials for starters than for C But from my humble understanding : C is more simple than cpp and I may make some software for my Ubuntu pc with C Anyway, probably learning cpp is better, but the question still stands...
Obligated mention: [CppCon 2015: Kate Gregory “Stop Teaching C"](https://www.youtube.com/watch?v=YnWhqhNdYyk)
180
cpp_questions
ulskr9
Well , the question is in the title , I've found **a lot** more websites that offer c++ courses/tutorials for starters than for C But from my humble understanding : C is more simple than cpp and I may make some software for my Ubuntu pc with C Anyway, probably learning cpp is better, but the question still stands...
They are separate languages. The important thing is that they have different idioms. What is good C is often bad C++. It's all too common that C programmers write a lot of really bad C++. But there are lessons you can learn from C expressly for the purpose of learning C++. Namely, you don't have to make a class for every god damn thing. The problem with C++ is people mistaken it as an OOP language. It's not, it's a multi-paradigm language, that only so happens to include OOP. It's also a functional language for almost as long as it's been an OOP language. The vast majority of the STL was donated to C++98 by HP from their in-house Functional Template Library. The point is, classes and inheritance should be among the last things you reach for from the toolbox when crafting a solution. C++ is indeed a huge language, and learning it is hard because while you can pick up on the syntax quicky, it's the idioms that you really need to master. You can write a lot of really terrible code in C++ by virtue of being a big language. Then again you can write a lot of terrible C code by virtue of being akin to high level assembler. It's not, of course, but the comparison is often made for a reason.
170
cpp_questions
ulswlv
I was just at the dentist who mentioned that he gets a lot of new mothers who need serious fillings or root canals, even if they had really healthy teeth pre-pregnancy and took good care of their dental health. I didn't get to ask deeply about it but physiologically, how does getting pregnant affect dental health so badly?
It has to do with nutrition and vitamins! Basically when people make jokes about babies being parasites, there is a reason for that. The body has to provide to make the baby, and it just so happens that calcium is one of the things they need a massive amount of- for all those bones and calcium rich body parts (like teeth!) It’s also why some folks bones become more fragile during pregnancy.
410
AskScience
ulswlv
I was just at the dentist who mentioned that he gets a lot of new mothers who need serious fillings or root canals, even if they had really healthy teeth pre-pregnancy and took good care of their dental health. I didn't get to ask deeply about it but physiologically, how does getting pregnant affect dental health so badly?
Pregnancy-induced Gingivitis is extremely common, and is caused by the fluxuations and different hormones one goes through whilst pregnant. This can make it more difficult to properly clean the teeth due to the swollen tissues, or even dissuade people from doing so because of bleeding and soreness. Also, morning sickness creates a higher acid level in the mouth which increases the rate of decay. And, even if there isn't vomitting, if there is heartburn/acid reflux/bile in the throat it does seep up into the oral cavit. And the growing pressure on the abdominal area only decreases the size of the stomach, which can also cause acid reflux. And don't get me started on frequent vomitting and its effect on teeth. (It can erode teeth very quickly and intensely.)
280
AskScience
ulswlv
I was just at the dentist who mentioned that he gets a lot of new mothers who need serious fillings or root canals, even if they had really healthy teeth pre-pregnancy and took good care of their dental health. I didn't get to ask deeply about it but physiologically, how does getting pregnant affect dental health so badly?
[removed]
90
AskScience
ultkcv
Could there be cave paintings containing animals we haven't found fossil records for yet? And if there were, how would we tell if the animal being depicted was actually real and not some made up creature?
Not as old as cave paintings but still pretty old is the Set animal. Some sort of canine with a forked tail, square ears and a long curved nose. Could be fanciful or a stylistic representation of a known animal or something that went extinct we haven't identified. Most experts lean to the fanciful, but we really don't know and the other gods are associated with real animals.
30,580
AskScience
ultkcv
Could there be cave paintings containing animals we haven't found fossil records for yet? And if there were, how would we tell if the animal being depicted was actually real and not some made up creature?
Not a cave painting, but there's always the case of the "[Meidum goose](https://news.artnet.com/art-world/extinct-goose-egypt-mona-lisa-1947028)". The Meidum mural is one of Egypt's most famous ancient artworks, a 4,600-year-old painting found in the tomb of a prince named Nefermaat. One of the most interesting details of the mural is a picture of two geese, which have traditionally been identified as red-breasted geese, a species native to Siberia and not found anywhere near Egypt. However, there are a number of differences between the geese in the mural and real red-breasted geese. The red areas on their faces and breasts are smaller, and they have larger white patches on their necks and cheeks. This has led to the suggestion that the Meidum geese are not, in fact, red-breasted geese at all, but the only known depiction of a goose native to Egypt that is now extinct. We already have remains of some animals that became extinct during the time of ancient Egypt, such as the Bennu heron (a giant heron that inspired the Egyptian mythical bird known as the Bennu), but not of these geese. Egypt, at the time, was much wetter than it is today, and a number of animals are depicted in ancient Egyptian art that are now either extinct worldwide or no longer found in Egypt.
10,240
AskScience
ultkcv
Could there be cave paintings containing animals we haven't found fossil records for yet? And if there were, how would we tell if the animal being depicted was actually real and not some made up creature?
We obviously know about horses, but there are petroglyphs of what appear to be horses and people on horseback in South America hundreds (possibly even thousands) of years after horses are believed to have gone extinct in the Americas. It is unclear if horses persisted within native oral tradition for dozens of generations (which is an incredible feat if true), or if horses persisted in areas long after the known fossil record indicates.
6,470
AskScience
ului03
Hi, I have a web service that does some reqwest calls to other services. I had quite a challenge to implement it in such a way that the request calls run in parallel, but only those that I need. In the end I got it working like this `let mut requests: Vec<Pin<Box<dyn Future<Output = Result<FeatureCollection>>>>> = vec![];` and then later `let mut responses: Vec<Result<FeatureCollection>> = futures::future::join_all(requests).await;` All requests return Featurecollections which is a geo format. So far so good. The web server was `actix_web`, and it worked. Now I need to migrate away from `actix` to `warp`, and this is where I run into problems. If I run this code in the handler pub async fn handler(mut body: impl Buf) -> Result<impl Reply, Rejection> { // call above code through async functions } The compiler complaints as follows: error: future cannot be sent between threads safely --> src/main.rs:24:10 | 24 | .and_then(handlers::plots::handler); | ^^^^^^^^ future returned by `handler` is not `Send` | = help: the trait `std::marker::Send` is not implemented for `dyn warp::Future<Output = std::result::Result<geojson::FeatureCollection, Rejection>>` note: future is not `Send` as this value is used across an await --> src/controllers/plots.rs:46:92 | 20 | let mut requests: Vec<Pin<Box<dyn Future<Output = Result<FeatureCollection>>>>> = vec![]; | ------------ has type `Vec<Pin<Box<dyn warp::Future<Output = std::result::Result<geojson::FeatureCollection, Rejection>>>>>` which is not `Send` ... 46 | let mut responses: Vec<Result<FeatureCollection>> = futures::future::join_all(requests).await; | ^^^^^^ await occurs here, with `mut requests` maybe used later I sort of get what the error means I think. apparently the trait Send is needed in order for this to work in a multithreaded environment, and Box/Pin don't implement that trait. But how do I fix it?
You can't implement Send yourself, the compiler is the one that decides if a type is Send or not. Read [this chapter](https://doc.rust-lang.org/book/ch16-03-shared-state.html) of the book, it describes how to share data between threads.
40
LearnRust
ulw45v
I was infusing some whiskey and had overfilled the bottle. I noticed when I attempted to force the cork on wood chips that had been floating quickly sank only to rise when I removed the cork. It was overfilled to the point there was no airgap so it didn't seem I was forcing air into the solution and shaking the bottle with the cork forced on didn't cause any change so it's more than currents from the motion of corking. My next guess was when you first cork the density at the top of the bottle was higher and it needed time to reach equilibrium. But the. Holding it for a minute or two the pieces never rose until I uncorked it again. I may be totally misremembering college physics but If I'm increasing pressure I should be slightly compressing the ethanol and increasing the density of it which increases the buoyant forces acting on the chips? My only guess is the increased pressure pushed fluid into airpockets in the wood forcing the air out, like cloth getting wet. But then why is it so easily reversible, when I release the cork how is air getting back into those pockets?
The increased pressure on the liquid could have compressed the air in the wood chips. That would increase the density of the wood chips, and they sink. When you take the cork out, pressure drops. The air bubbles in the wood chips push the liquid back out, density drops, and the chips float. The air might be staying in the chips, just shrinking and expanding as the liquid pressure changes.
70
AskScience
ulw45v
I was infusing some whiskey and had overfilled the bottle. I noticed when I attempted to force the cork on wood chips that had been floating quickly sank only to rise when I removed the cork. It was overfilled to the point there was no airgap so it didn't seem I was forcing air into the solution and shaking the bottle with the cork forced on didn't cause any change so it's more than currents from the motion of corking. My next guess was when you first cork the density at the top of the bottle was higher and it needed time to reach equilibrium. But the. Holding it for a minute or two the pieces never rose until I uncorked it again. I may be totally misremembering college physics but If I'm increasing pressure I should be slightly compressing the ethanol and increasing the density of it which increases the buoyant forces acting on the chips? My only guess is the increased pressure pushed fluid into airpockets in the wood forcing the air out, like cloth getting wet. But then why is it so easily reversible, when I release the cork how is air getting back into those pockets?
Liquids are often not noticeably compressible under normal human temperatures and pressures. Is it possible that what happened is the compression was (near) entirely forced on the cork which was compressed until it no longer displaced its weight and therefore lost buoyancy?
60
AskScience
ulw45v
I was infusing some whiskey and had overfilled the bottle. I noticed when I attempted to force the cork on wood chips that had been floating quickly sank only to rise when I removed the cork. It was overfilled to the point there was no airgap so it didn't seem I was forcing air into the solution and shaking the bottle with the cork forced on didn't cause any change so it's more than currents from the motion of corking. My next guess was when you first cork the density at the top of the bottle was higher and it needed time to reach equilibrium. But the. Holding it for a minute or two the pieces never rose until I uncorked it again. I may be totally misremembering college physics but If I'm increasing pressure I should be slightly compressing the ethanol and increasing the density of it which increases the buoyant forces acting on the chips? My only guess is the increased pressure pushed fluid into airpockets in the wood forcing the air out, like cloth getting wet. But then why is it so easily reversible, when I release the cork how is air getting back into those pockets?
[removed]
30
AskScience
ulx2s9
Where did you attend college, what years, and what was the overall experience like?
Undergrad is in agriculture from a college in the Deep South. If you’ve seen Letterkenny, it was that, but without hockey.
30
AskOldPeople
ulx2s9
Where did you attend college, what years, and what was the overall experience like?
It was great being away from my awful parents, but my fellow students were such dumbasses. People will reminisce about the great friends they still have from college and I'll wonder why the fuck there didn't seem to be anyone great at my college.
30
AskOldPeople
ulx2s9
Where did you attend college, what years, and what was the overall experience like?
Went straight from high school in '77 to working in a publishing career. Lied a little in the interview. Fake it till ya make it. Seems like a lifetime ago. Oh, it was!
30
AskOldPeople
ulxe65
What was it like living during the AIDS/HIV crisis, was it scary?
It was the best of times, it was the worst of times. In 1980 at age 22 I took a semester off, moved to Austin, Texas and jumped into the gay crowd with both feet. I made a number of good friends, almost all of them are dead now. The first couple years of the decade were a blast. Then the plague came. Some people were terrified, others were stunned and became reclusive (for many, it was too late). After the test came out in 85(?), the first question acquaintences would ask is "did you get / are you getting the test." I didn't for some years, more on that below. Society in general was still freaking out - absolute hysteria. Everyone was afraid, some with good reason (\*raises hand*) but a fuckload of people were just reacting hysterically. You never saw someone go into the hospital, but people were disappearing from the scene and we didn't bother wondering what happened to them. A lot of people did like me, and tried to ignore it, but I did start having safer sex. So for me, the latter part of the decade was spent expecting to get sick and die at some point before too long. When I had returned to school in 89, I just assumed that I was infected. Turns out I was right but I wouldn't know that for another years and a half. During which time I met a guy and fell in love. When we hit "move in together" we decided that it was probably best too know for sure. Not because there was much that could make a difference in the end but for his sake. So in 91 I got tested. Funny story - the counselor was a friend of his, an acquaintence for me, and when we went to get the test results she was more rattled by my being HIV+ about it than either of us was. He was an AIDS educator, we had discussed it a lot, and I had been prepping myself for years. He promised to stick by me to the end. I had so few CD4 cells that I was thinking about giving them names, so we expected the end to happen fairly soon - doctors gave me six to twelve months. (HAH HAH, I say in Nelson Muntz's voice - I didn't die ppthhpththtp.) Somehow I managed to stay alive, we never had to do the home hospice thing, and next month we'll celebrate the 30th anniversary of our commitment ceremony.
2,510
AskOldPeople
ulxe65
What was it like living during the AIDS/HIV crisis, was it scary?
I studied for my doctorate with two people, one of whom (a gay man) had AIDS. He was a funny, brave, smart, wonderful person. We helped each other prepare for orals and our dissertation defenses. At first we didn't realize he was sick but then he began to fail quickly. I went to visit him in the hospital and this was at the height of people treating those with AIDS as if they were lepers. The fourth or fifth time I visited it was clear he wouldn't last much longer. In addition to everything else he suffered (rife with Kaposi's sarcoma), he seemed fearful. I remember holding his hand, and how he suddenly found some physical strength in how tightly he gripped mine. When I was leaving I knew in my heart that all the fears about touching someone with AIDS were wrong and that it wasn't a guarantee you would Catch It Too. I bent over to kiss him on the head and we embraced. I knew we were saying goodbye. There was not widespread, casual acceptance of alternate lifestyles in the Reagan era. The terrible things people said about gay men at that time are now kind of coming back to me in the hateful way that people interact today regarding some political issues. He was a kindhearted, witty, good person; he passed away a few months before getting his degree conferred. Myself, our co-studier, and our professors paid tribute to him at the convocation. It was an impossibly sad time, there was so much sadness it's hard to explain, and so many fine people were lost. Will always miss you, Doug.
1,910
AskOldPeople
ulxe65
What was it like living during the AIDS/HIV crisis, was it scary?
As someone who was (as far as I knew then) straight, not promiscuous (i.e., a loser), and living in a place (Trenton NJ) not particularly known as a gay hotspot? It was still fucking terrifying. Yeah, it was originally billed as "Gay Cancer," but it was pretty quickly established that it's not a gay disease. Anyone could get this thing. I moved to San Francisco in 1996, when I was just turning 23. Made friends with many, many people who were DIRECTLY affected by AIDS - lost loved ones or were HIV positive. The stories are bone-chilling, horrible, they made me literally weep out of empathy.
1,280
AskOldPeople
ulxgmo
Hi Everyone, Here is my Matrix Multiplication C++ OpenMP code that I have written. I am trying to use OpenMP to optimize the program. The sequential code speed was 7 seconds but when I added openMP statements but it only got faster by 3 seconds. I thought it was going to get much faster and don't understand if I'm doing it right. The OpenMP statements are in the fill\_random function and in the matrix multiplication triple for loop section in main. I would appreciate any help or advice you can give to understand this! ​ #include <iostream> #include <cassert> #include <omp.h> #include <chrono> using namespace std::chrono; double** fill_random(int rows, int cols ) { double** mat = new double* [rows]; //Allocate rows. #pragma omp parallell collapse(2) for (int i = 0; i < rows; ++i) { mat[i] = new double[cols]; // added for( int j = 0; j < cols; ++j) { mat[i][j] = rand() % 10; } } return mat; } double** create_matrix(int rows, int cols) { double** mat = new double* [rows]; //Allocate rows. for (int i = 0; i < rows; ++i) { mat[i] = new double[cols](); //Allocate each row and zero initialize.. } return mat; } void destroy_matrix(double** &mat, int rows) { if (mat) { for (int i = 0; i < rows; ++i) { delete[] mat[i]; //delete each row.. } delete[] mat; //delete the rows.. mat = nullptr; } } int main() { int rowsA = 1000; // number of rows int colsA= 1000; // number of coloumns double** matA = fill_random(rowsA, colsA); int rowsB = 1000; // number of rows int colsB = 1000; // number of coloumns double** matB = fill_random(rowsB, colsB); //Checking matrix multiplication qualification assert(colsA == rowsB); double** matC = create_matrix(rowsA, colsB); //measure the multiply only const auto start = high_resolution_clock::now(); //Multiplication #pragma omp parallel for for(int i = 0; i < rowsA; ++i) { for(int j = 0; j < colsB; ++j) { for(int k = 0; k < colsA; ++k) //ColsA.. { matC[i][j] += matA[i][k] * matB[k][j]; } } } const auto stop = high_resolution_clock::now(); const auto duration = duration_cast<seconds>(stop - start); std::cout << "Time taken by function: " << duration.count() << " seconds" << std::endl; //Clean up.. destroy_matrix(matA, rowsA); destroy_matrix(matB, rowsB); destroy_matrix(matC, rowsA); return 0; }
Move the `matC[i][j]` assignment out of the loop. And pls, no more nested arrays. Double indirection on every element access isn't a great idea. Just use 1D `std::vector`. *And if I enable AVX2+fp:fast on MSVC, I get FMA instructions. *`std::for_each(std::execution::par` appears to be slightly faster, but you need an index iterator. *I'm getting this inner loop: 00007FF6BE8417A2 vmovsd xmm0,qword ptr [r8-10h] 00007FF6BE8417A8 vfmadd231sd xmm2,xmm0,mmword ptr [r9+r13*8] 00007FF6BE8417AE vmovsd xmm0,qword ptr [r8-8] 00007FF6BE8417B4 vfmadd231sd xmm2,xmm0,mmword ptr [r9+r15*8] 00007FF6BE8417BA vmovsd xmm1,qword ptr [r8] 00007FF6BE8417BF vfmadd231sd xmm2,xmm1,mmword ptr [r9] 00007FF6BE8417C4 vmovsd xmm0,qword ptr [r8+8] 00007FF6BE8417CA vfmadd231sd xmm2,xmm0,mmword ptr [r9+r12*8] 00007FF6BE8417D0 add r9,r14 00007FF6BE8417D3 lea r8,[r8+20h] 00007FF6BE8417D7 sub rcx,1 00007FF6BE8417DB jne `main'::`4'::<lambda_1>::operator()+0D2h (07FF6BE8417A2h) Oddly, when I do it the "cache friendly" way (with `vfmadd231pd`), it's much slower. *https://codereview.stackexchange.com/questions/177616/avx-simd-in-matrix-multiplication *https://gist.github.com/nadavrot/5b35d44e8ba3dd718e595e40184d03f0 *A simple blocking gives a decent speed up: for (int j = 0; j < localColsB; j += 8) { double x[8]{}; for (int k = 0; k < localColsA; ++k) for (int jj = 0; jj < 8; ++jj) x[jj] += rowA[k] * localMatB(k, j + jj); for(int jj = 0; jj < 8; ++jj) rowC[j + jj] = x[jj]; } *Fixed bug. Cache friendly version is much faster. 30ms on 12600. Same result hash as original code.
30
cpp_questions
ulxixy
I’ve been obsessed with aging recently (not in a good way, mind you) and I can’t help but notice that I’ve yet to meet a single person who’s 40 or older that still has fun like they did in their teens, 20s, and 30s. Does anyone still get drunk as fuck at parties? Is romance still exciting? Do wild ass things still happen to you that’ll be stories you tell for years to come? I’m terrified of life becoming as boring as it seems when I look at all the older people I know.
Do people still do some of that? Sure. But I don't, and I have awesome times. As you get older what you find enjoyable changes. I mean, in another universe there's someone who's posted to r/ask20somethings asking "do people in their 20s and 30s still have fun? I mean like, watching cartoons, going down the slide FRONTWARDS AND BACKWARDS, drinking whole sodas? I'm 11 now and it just seems like people in their 20s seem to be boring as shit"
1,270
AskOldPeople
ulxixy
I’ve been obsessed with aging recently (not in a good way, mind you) and I can’t help but notice that I’ve yet to meet a single person who’s 40 or older that still has fun like they did in their teens, 20s, and 30s. Does anyone still get drunk as fuck at parties? Is romance still exciting? Do wild ass things still happen to you that’ll be stories you tell for years to come? I’m terrified of life becoming as boring as it seems when I look at all the older people I know.
Absolutely still having a blast in my 50s. Just not doing stupid shit like I did in my 20s.
540
AskOldPeople
ulxixy
I’ve been obsessed with aging recently (not in a good way, mind you) and I can’t help but notice that I’ve yet to meet a single person who’s 40 or older that still has fun like they did in their teens, 20s, and 30s. Does anyone still get drunk as fuck at parties? Is romance still exciting? Do wild ass things still happen to you that’ll be stories you tell for years to come? I’m terrified of life becoming as boring as it seems when I look at all the older people I know.
I had _more_ fun in my 40s than in my 20s. Including great parties, great travel experiences, awesome friends. I’ve had much more exciting romance in my 40s than in my 20s. I love going to metal gigs. I still get somewhat drunk sometimes, but “getting drunk as fuck at parties” really does get boring as you get older, so I wouldn’t call that fun. Your idea of fun changes as you get older. When I hear my step daughter talking with her friends about partying and going out that sounds mind numbingly boring to me. And of course she thinks what my gf and I talk about is boring as well. So you may not be meeting many 40yr olds you think aren’t boring, but that’s just because those 40yr olds aren’t interested in the same stuff young people are into.
420
AskOldPeople
ulzraf
Edit: I was thinking about kidney and liver transplants, where the donor may still be alive.
Interesting question. Broadly, there are three types of rejection: hyperacute, acute and chronic. In hyperacute rejection the organ gets damaged really quickly by premade antibody and immune cell activity. I reckon by the time this was diagnosed the organ would be pretty badly damaged. In acute and chronic rejection there is an influx of immune cells which recognise the organ as foreign. In general, this process is recognised by deteriorating graft function, and treated by altering immunosuppression. In this case there are two issues. The first is that organ dysfunction has already occurred. This is not necessarily irreparable, but makes retransplanting an organ a challenging proposition. The other is that the organ is now suffused with immune cells from the recipient, so transplanting these back into the original donor may have some negative effect, similar to graft Vs host disease. Except we already know they are primed against the donors cells, and theres a lot of inflammation around, so even more risky. These issues, combined with the fact that you wouldn't take an organ from someone who couldn't tolerate losing it, and the ever present risk of major surgery, mean that it would never be in the donors best interest to get a retransplant of their own organ. I can't find any literature on the issue on a cursory look, but will update if I find anything. And am always happy to be corrected. Edit: [This](https://onlinelibrary.wiley.com/doi/10.1111/ctr.14554) paper talks about retransplanting transplanted kidneys in the absence of rejection into new recipients (I.e. not the original donor). It has happened 4 times in Europe in the past 20 years. It shows at least that a previously transplanted kidney can be retransplanted safely.
1,180
AskScience
ulzraf
Edit: I was thinking about kidney and liver transplants, where the donor may still be alive.
Unfortunately for most organ transplants the donor is dead, so it wouldn't be much use to them. The time window for transplants is pretty small and the rejection would damage the organ really badly, so I doubt it would be much use to anyone else either
290
AskScience
ulzraf
Edit: I was thinking about kidney and liver transplants, where the donor may still be alive.
Well there are instances of healthy donor organs being re-donated and used if that person were to die, but I think if the organ were rejected it would be too damaged to be useful in anyone else. As far as being given back to the donor I don't think that would be possible because of blood supply issues. Like you could remove Kidney A and later put it where B is, but you couldn't put it back where it originally was because the blood supply would no longer be there. But I could be wrong.
70
AskScience
um18by
Hi. I came across an AI engineer mentioning in an interview that "AI is just compression". I was struggling to understand what this means. I figured he was talking about the link of information theory to AI but not sure. He also mentioned the hutter prize which led him to this epiphany of "AI is just compression". It seems like a gross oversimplification but maybe there is some logic in there that I am unable to understand. Also, can you guys point me towards some resources on this topic. I would love to learn more about "AI is just compression" ​ Edit: I am talking about these 2 things [https://en.wikipedia.org/wiki/Hutter\_Prize](https://en.wikipedia.org/wiki/Hutter_Prize) [https://youtu.be/boiW5qhrGH4](https://youtu.be/boiW5qhrGH4)
EDIT: There's some criticism of my use of the term "AI" versus "ML". I'm answering the question as I think OP intended it, which is covering the subset of AI which is popular today, which is really ML. So if you read this, and it bugs you that I use AI, please read ML instead, it's what I really mean. If it's not immediately obvious to you why there's a difference or distinction between AI and ML, then there are some interesting discussion in this thread about it. It’s probably better to start by saying “AI is just statistics”. Most AI techniques boil down to [curve fitting](https://en.m.wikipedia.org/wiki/Curve_fitting) (effectively). You take a bunch of data points and try to come up with a function which would generate those same data points given the same inputs (for input/output pairs you already know) and the “right” output for inputs where you don’t already know the answer. The big difference with AI is how many data points you feed in to your fitting process, and how many dimensions your curve function has. Dimensions means the number of inputs and outputs. You might have trillions of data points you’re fitting and and your curve might have thousands of dimensions. Taking a huge amount of data and finding a way to represent that data as a (relatively) simple curve or function is “just compression”. So it’s ok to say that “AI is just compression” You won’t really find a book or text on this topic. It’s just a cute observation by someone who knows the subject matter really well. It’s kind of an oversimplification, but it’s a good one.
480
AskComputerScience
um18by
Hi. I came across an AI engineer mentioning in an interview that "AI is just compression". I was struggling to understand what this means. I figured he was talking about the link of information theory to AI but not sure. He also mentioned the hutter prize which led him to this epiphany of "AI is just compression". It seems like a gross oversimplification but maybe there is some logic in there that I am unable to understand. Also, can you guys point me towards some resources on this topic. I would love to learn more about "AI is just compression" ​ Edit: I am talking about these 2 things [https://en.wikipedia.org/wiki/Hutter\_Prize](https://en.wikipedia.org/wiki/Hutter_Prize) [https://youtu.be/boiW5qhrGH4](https://youtu.be/boiW5qhrGH4)
Are you sure he said AI and not machine learning? Machine learning can be seen as function estimation. For a given ML problem, there is some true function which is either intractable or unknown, and the task of ML is to come up with a good guess of a function that gets the right answers most of the time (or perhaps we make the stronger claim of getting right answers to within a formally bounded degree of correctness). This can be seen as a form of compression. The mapping of problem cases to answers is the uncompressed data, the true function is the output of lossless compression (assuming no noise in the data set), and the ML-discovered function is the output of lossy compression. It seems like overstating the case to say that ML _is_ compression, though. And certainly there's more to AI than just ML, and a lot of the non-ML parts of AI don't seem to be about compression. (Except in the trivial sense that all cognition is kinda-sorta about compression: when we come up with a category like "tree" or "dog" and classify certain objects into it, we are using "compression" to avoid the mental effort that would otherwise be required to know the properties of every individual object.)
160
AskComputerScience
um18by
Hi. I came across an AI engineer mentioning in an interview that "AI is just compression". I was struggling to understand what this means. I figured he was talking about the link of information theory to AI but not sure. He also mentioned the hutter prize which led him to this epiphany of "AI is just compression". It seems like a gross oversimplification but maybe there is some logic in there that I am unable to understand. Also, can you guys point me towards some resources on this topic. I would love to learn more about "AI is just compression" ​ Edit: I am talking about these 2 things [https://en.wikipedia.org/wiki/Hutter\_Prize](https://en.wikipedia.org/wiki/Hutter_Prize) [https://youtu.be/boiW5qhrGH4](https://youtu.be/boiW5qhrGH4)
Your brain doesn't actually store data but it learns how to reproduce by conditioning your neurones. Instead of storing big amounts of data, you can train a set of neurones, which will consume less space compared to the data itself, hence compression. It won't be bit perfect though. Using AI for *real* compression is not a good solution.
30
AskComputerScience
um1faj
What signals are they receiving and why would an enemy plane or munition emit these signals in the first place?
>What signals are they receiving Imagine you're hiding in a dark room. And you know someone is looking for you: because in that darkness you can see someone using a flashlight, inspecting every dark corner where you might be hiding ... It's the same thing with whatever electromagnetic signal you're using to find and track enemy airplanes: There's got to be a constant stream (like a flashlight in a dark room) of signals (e.g. radio waves emitted by a radar) in order to see anything. Back to you in the dark room: How do you know you were found? Because the person holding the flashlight is shining the light directly into your face, dead on, and they have stopped looking into other corners ... They obviously know exactly where you are, right? Same thing with e.g. radar-tracking: Once a radar is starting to track and aim at a target that airplane will know it's being aimed at because there will be a constant beam of radio waves in frequencies that are very typical for a radar... In modern military airplanes the radar warning should go off and warn the pilot that he's being aimed at. Same thing if you use other tracking methods, e.g. laser: Modern military airplanes and helicopters have a laser-warning sensor too. ​ >why would an enemy plane or munition emit these signals in the first place? See the analogy with the dark room: how are you going to find someone in a very very dark room without a flashlight? Stumble in blindly and just touch everything, hoping your sense of touch will do the job? Yell and shout into the room and politely ask the other person to come out? The flashlight is the easiest and safest way. Same thing with finding and tracking enemy airplanes: you have to emit signals (e.g. radar) or else you're blind. But it also means that the other side can detect where that signal came from... It's a "cat and mouse" game.
600
AskScience
um1faj
What signals are they receiving and why would an enemy plane or munition emit these signals in the first place?
In short, the different mechanisms for achieving the lock can be detected. Active radar homing has a radar in the missile sending out signals. Those signals can be detected and classified by the target aircraft. Passive radar homing has a receiver in the missile reacting to specific signals bounced off of the target by the launching system. To your question about “why would it be built that way”, in order for the attacking plane’s lock to work, those signals need to be in place. No one has created a way to effectively mask the signal in a way that would persist the target lock. So, science to mask the signal hasn’t caught up with science to achieve the lock in the first place.
90
AskScience
um1faj
What signals are they receiving and why would an enemy plane or munition emit these signals in the first place?
Combat aircraft will have an RWR (radar warning receiver). This will alert them to the radar signals of various possible threats. Most RWR's will be able to tell the difference between various threats, like a specific type of enemy aircraft, or specific type of surface to air missle system. It also knows when one of the threats is specifically tracking them, or "locking them up". It knows this because instead of seeing a blip of radar energy every few seconds as the radar sweeps across the sky, it sees a constant focus of radar on them as the tracking radar basically points right at them.
30
AskScience
um28lu
i.e. the '60s, '70s, etc...
The 2020s already seem like a full fricking decade.
210
AskOldPeople
um28lu
i.e. the '60s, '70s, etc...
2020
210
AskOldPeople
um28lu
i.e. the '60s, '70s, etc...
The 80s, simply because I spent so much of them waiting to be older, to be out of high school, out of my parents house and away from the boring, parochial, minuscule town they'd settled in.
80
AskOldPeople
um4vqh
Imagine a struct, having 5 doubles as members + implicit constructors. An instance of this obj is passed to a function by value. Before the function does anything, in the debugger you see that the members are different than their assignments. What might be modifying this copy constructed temp object? We had to pass the obj by reference to solve the issue.
Maybe nothing was wrong and the function simply didn't set itself up yet.
120
cpp_questions
um4vqh
Imagine a struct, having 5 doubles as members + implicit constructors. An instance of this obj is passed to a function by value. Before the function does anything, in the debugger you see that the members are different than their assignments. What might be modifying this copy constructed temp object? We had to pass the obj by reference to solve the issue.
The function will expand the stack space to accommodate your struct, and then copy the values from the callee into that space. Before the copy, however, the struct will contain uninitialized values - garbage left over from previous calls. With the debugger, always assume that the function starts at the *first statement* inside the scope.
50
cpp_questions
um5fkv
There are some movies that whenever they are on, I have to stop what I am doing and watch them. Yes, I've seen them TONS of time but they grab me everytime. Know what I mean? What are yours? \#1 Shawshank Redemption \# 2 Peggy Sue Got Married \# 3 Die Hard
You may not like my answer, since it's not a movie (well, it *was* a movie, but. . .), but anytime I come across an episode of M.A.S.H. I always watch. It doesn't matter that I've seen every episode a half-dozen times.
360
AskOldPeople
um5fkv
There are some movies that whenever they are on, I have to stop what I am doing and watch them. Yes, I've seen them TONS of time but they grab me everytime. Know what I mean? What are yours? \#1 Shawshank Redemption \# 2 Peggy Sue Got Married \# 3 Die Hard
On the lighter side *The Princess Bride* is not something I'll miss if available and for something more dramatic *Master and Commander: The Far side of the World* with Russell Crowe. Is there a better period style actor out there? *Gladiator* is another solid historical movie.
240
AskOldPeople
um5fkv
There are some movies that whenever they are on, I have to stop what I am doing and watch them. Yes, I've seen them TONS of time but they grab me everytime. Know what I mean? What are yours? \#1 Shawshank Redemption \# 2 Peggy Sue Got Married \# 3 Die Hard
O Brother Where Art Thou
240
AskOldPeople
um5gwq
I'm asking this as a fellow "old person". (44 F). Is there a meal service geared toward senior citizens? My mom, who just turned 75, barely eats anything. She's maybe 90 pounds. She has to do a low sodium diet per her doctor because of heart problems. She doesn't like to cook so she eats mostly toast with jam or TV dinners. Those aren't low sodium but it's basically all she eats in a day. I know there are meal delivery services like Hello Fresh where they send you ingredients to cook every week unless you opt out. She's looking for precooked meals that you just heat up. But it seems like most of these are geared towards a family, there is no "single " option unless you want to pay top dollar. Another difficulty is she doesn't have any internet service. Meals on Wheels wouldn't work for her as she's a capable adult who can drive. She's willing to pay. Is there anything she can do?
I don’t know the answer as an “old person”, but as a nurse of 30 years, I’d call her doctor, tell him/her your concerns, and let the multitude of social service options rain on your mother. I know it seems overwhelming, but there really is a way in this country to feed the elderly; if you need reassurance, send me a DM, tell me where you live, and I’m happy to research your options. Got your back, and thanks for caring so much about your mom; in my experience, that’s not always happening. Take care.
200
AskOldPeople
um5gwq
I'm asking this as a fellow "old person". (44 F). Is there a meal service geared toward senior citizens? My mom, who just turned 75, barely eats anything. She's maybe 90 pounds. She has to do a low sodium diet per her doctor because of heart problems. She doesn't like to cook so she eats mostly toast with jam or TV dinners. Those aren't low sodium but it's basically all she eats in a day. I know there are meal delivery services like Hello Fresh where they send you ingredients to cook every week unless you opt out. She's looking for precooked meals that you just heat up. But it seems like most of these are geared towards a family, there is no "single " option unless you want to pay top dollar. Another difficulty is she doesn't have any internet service. Meals on Wheels wouldn't work for her as she's a capable adult who can drive. She's willing to pay. Is there anything she can do?
I volunteer for Meals on Wheels in my area. At least here,there is no restriction based on ability to drive. If you need/want the service,you can participate. If low income,there are subsidies. If not,you can pay the full price. However,the meals are not low sodium or made with individual dietary concerns. I myself ,age 64 ,use Daily Harvest,which is plant based,very healthy and frozen. You heat up in microwave or toss in blender for smoothies. Pretty tasty. Not cheap but not overly expensive in my opinion. You could order for your mom based on her preferences. Also,sometimes eating alone is not enjoyable and some company at mealtimes makes all the difference in how much food is consumed.
100
AskOldPeople
um5gwq
I'm asking this as a fellow "old person". (44 F). Is there a meal service geared toward senior citizens? My mom, who just turned 75, barely eats anything. She's maybe 90 pounds. She has to do a low sodium diet per her doctor because of heart problems. She doesn't like to cook so she eats mostly toast with jam or TV dinners. Those aren't low sodium but it's basically all she eats in a day. I know there are meal delivery services like Hello Fresh where they send you ingredients to cook every week unless you opt out. She's looking for precooked meals that you just heat up. But it seems like most of these are geared towards a family, there is no "single " option unless you want to pay top dollar. Another difficulty is she doesn't have any internet service. Meals on Wheels wouldn't work for her as she's a capable adult who can drive. She's willing to pay. Is there anything she can do?
Get an Instant Pot or slow cooker, make soup or stew by the gallon, and freeze it for her in individual microwave containers. You can do several different batches so that she’s always got some variety.
80
AskOldPeople
um8ehb
Hi, I've been trying to cross compile my C++ code using the "-arch i386" and GCC outputs that it's deprecated for mac OS. I just wanted to know if there is any work around.
Cross-compile it to what target? You could also compile up your own toolchain. But afaik: macOS stopped supporting 32-bit some time ago.
90
cpp_questions
um8nb0
I've been using Dev C++, but it often crashes/closes itself and I lose all unsaved stuff. I've already tried Visual Studio Code (couldn't make it work correctly), Code::Block (it doesn't seems to have skin support?). If those are the best IDEs, how do I compile by cli? I don't really mind using notepad++. lol...
You making your life hell. Download visual studio 2022 community edition. And make it easy on yourself.
130
cpp_questions
um8t09
I am asking because I am learning remotely and trying to prioritize which subjects to focus on. Like how much should they know about each of these topics more or less and which matter the most? Are any other points more important that I should have included? Or are there too many types of jobs using C++ to make any generalizations? To be clear, me being able to make this list only means that I at least know that each item exists, not that I already know a lot about each of them, that is why I am asking this: * Classes, Objects, Constructors, and Destructors * Data Types and Keywords * Namespaces * Overloading Operators * Inheritance * Polymorphism * Move Semantics * Smart Pointers & RAII * Exception Handling * I/O and Streams * Iterators * <Algorithm> * STL * Lambdas, Function Objects and Function Pointers * Generic Templating * Creating and Linking Libraries * Cmake * Unit Testing * Concurrency * 3rd Party Libraries * Data Structures * Sorting Algorithms * IPC * Debuggers * Differences between Compilers * Using Different Compiler Flag Options * Memory Debugging, Memory Leak Detection, and Profiling * Differences between the C++ Standards * Differences between Operating Systems * Different Ways of Allocating Thank you
What very often people do not want to admit is that you are expected to know all of this in entry level. What is not expected is how to combine all of this to solve a problem.
560
cpp_questions
um8t09
I am asking because I am learning remotely and trying to prioritize which subjects to focus on. Like how much should they know about each of these topics more or less and which matter the most? Are any other points more important that I should have included? Or are there too many types of jobs using C++ to make any generalizations? To be clear, me being able to make this list only means that I at least know that each item exists, not that I already know a lot about each of them, that is why I am asking this: * Classes, Objects, Constructors, and Destructors * Data Types and Keywords * Namespaces * Overloading Operators * Inheritance * Polymorphism * Move Semantics * Smart Pointers & RAII * Exception Handling * I/O and Streams * Iterators * <Algorithm> * STL * Lambdas, Function Objects and Function Pointers * Generic Templating * Creating and Linking Libraries * Cmake * Unit Testing * Concurrency * 3rd Party Libraries * Data Structures * Sorting Algorithms * IPC * Debuggers * Differences between Compilers * Using Different Compiler Flag Options * Memory Debugging, Memory Leak Detection, and Profiling * Differences between the C++ Standards * Differences between Operating Systems * Different Ways of Allocating Thank you
You get paid to get shit done, not how many language feature checkboxes you can tick off. The programming language is just scratching the surface of what’s important in a software engineering job.
270
cpp_questions
um8t09
I am asking because I am learning remotely and trying to prioritize which subjects to focus on. Like how much should they know about each of these topics more or less and which matter the most? Are any other points more important that I should have included? Or are there too many types of jobs using C++ to make any generalizations? To be clear, me being able to make this list only means that I at least know that each item exists, not that I already know a lot about each of them, that is why I am asking this: * Classes, Objects, Constructors, and Destructors * Data Types and Keywords * Namespaces * Overloading Operators * Inheritance * Polymorphism * Move Semantics * Smart Pointers & RAII * Exception Handling * I/O and Streams * Iterators * <Algorithm> * STL * Lambdas, Function Objects and Function Pointers * Generic Templating * Creating and Linking Libraries * Cmake * Unit Testing * Concurrency * 3rd Party Libraries * Data Structures * Sorting Algorithms * IPC * Debuggers * Differences between Compilers * Using Different Compiler Flag Options * Memory Debugging, Memory Leak Detection, and Profiling * Differences between the C++ Standards * Differences between Operating Systems * Different Ways of Allocating Thank you
I would argue everything from the first block. However, you don't have to know everything in detail. For example: You should know how to use streams, though special stuff as using std::fill I've never used in my 10 year career. Even when useful, I would expect someone to give you std::format instead. I wouldn't expect you to know the second block (given some exceptions like unit testing), i do expect that they'll teach you where relevant. In general, I'm convinced when you are able to demonstrate usage of algorithms and unique_ptr. This combines containers and their iterators, lambdas, RAII, templates (calling them), function overloading, lifetime ... Afterwards, I would expect you to be able to explain what you did and how it works. I believe that when you are able to understand this, you can learn everything else. So if you never used a function pointer, some googling or asking around will most likely be sufficient to use it in its basic form. When a company is deep into something, I would expect them to either be explicit about it or teach you. It's not acceptable to assume any developer to understand the whole of c++
50
cpp_questions
um9oz4
Hi guys, nooby question from an electronics tinkerer. For reference this is for a microcontroller with very minimal resources. The WiFi api for my microcontroller (ESP32) requires me to set a struct member that is a `uint8_t[32]` for the SSID. The docs simply showed `xyz.ssid = "name"` but that gives the error "must be modifiable lvalue". A typecast gives an error for loss of precision. I've tried implementing a c-string strcpy, but can't make it work. I ended up implementing a disgusting process of setting each ssid array element to an individual char to make it work but it feels hacky and wrong. I'm sure there is a better way to do this, can anyone help?
> For reference this is for a microcontroller with very minimal resources and I'm trying to avoid including lots of headers. These two statements do not correlate. A header does not have any runtime overhead in and of itself. The code in the headers is likely much more optimised that what you or I could write.
60
cpp_questions
um9vff
Which book does it exactly refers to?
Are you asking about "a book that specifically provides an introduction to programming"? There are tons of intro books out there, and I don't think they're referring to a specific one. Here's my favorite: https://openbookproject.net/thinkcs/python/english3e/
140
LearnRust
um9vff
Which book does it exactly refers to?
It’s not referring to a literal book. [The book](https://doc.rust-lang.org/book/) is just a Medium sized online course so that you can get started with rust.
120
LearnRust
umb4gq
Can non alcoholic beer grow botulism , especially If the cans are a little swollen at the top and one of the bottoms of the cans was popped outwards. You always hear about how you should never consume anything from a swollen or dented can, but what is the likelihood of botulism spores growing in a commercially sold non alcoholic beer?
The most important component for botulism risk is pH. The sterilized canning method is a primary means of safety but having acidity in the food is considered a secondary safety barrier. A swollen can is likely over-pressure caused by secondary fermentation, spoilage, or freezing. Botulinum growth of course doesn't necessary produce any noticeable signs of spoilage so something appearing fine could in fact be contaminated with toxin. Botulinum spores are ubiquitous in the environment so improper canning technique should be assumed to be contaminated and unsafe for consumption. This precisely why we commonly see headlines like these: [Soul Cedar Farm recalls peppers over Clostridium botulinum contamination](https://www.foodsafetynews.com/2022/04/soul-cedar-farm-recalls-peppers-over-clostridium-botulinum-contamination/) CDC of course recommends "When in doubt, throw it out" which is really great advice. Botulism really, really sucks. [https://www.cdc.gov/botulism/consumer.html](https://www.cdc.gov/botulism/consumer.html)
40
AskScience
umb7p8
In my custom class I would like to overload & operator so that it returns the address of a member variable. Is this a safe approach as I assume it would make it impossible to get the address of the class object or should I just use a 'getMemberAddr()' function
> I assume it would make it impossible to get the address of the class object It would still be possible using [`std::address_of`](https://en.cppreference.com/w/cpp/memory/addressof). In general, it is highly discouraged to overload the unary `&` operator. I think adding the `getMemberAddr()` function would be a better approach. Alternatively, you might also consider having an accessor `getMember()`, having it return a (potentially const) reference, and using it like so `&obj.getMember()`. I think this is a bit more consistent with how most people write accessors.
80
cpp_questions
umb7p8
In my custom class I would like to overload & operator so that it returns the address of a member variable. Is this a safe approach as I assume it would make it impossible to get the address of the class object or should I just use a 'getMemberAddr()' function
The important consideration to make is how confusing this implementation will be to someone who's seeing it with no context. Operators are defined with a very specific set of semantics in mind. If you start changing what those semantics mean, your code suddenly becomes unintelligible to anyone not already familiar with it, or worse, apparently intelligible but secretly doing something unexpected behind-the-scenes.
30
cpp_questions
umbn40
I am just curious if it is better practice to use a macro instead of creating a new variable? void csvParser::formatImportCell(csvCell& _cell) { std::string& cellReference = _cell.getCellReference(); // #define cellReference _cell.getCellReference() // Remove enclosing quotes if (cellReference[0] == '\"') { stringLibrary::chopLeft(cellReference, 1); stringLibrary::chopRight(cellReference, 1); } // Remove double quotes stringLibrary::replace(cellReference,"\"\"", "\""); // #undef cellReference } in this case, I would replace the variable with the macro to the function. (If I remember correctly I should also use Macros as all caps lock, but I have just left it with the same as the variable name for clarity)
Using a macro in modern C++ is (almost) never a good idea. You should try to never have to use them.
90
cpp_questions
umbn40
I am just curious if it is better practice to use a macro instead of creating a new variable? void csvParser::formatImportCell(csvCell& _cell) { std::string& cellReference = _cell.getCellReference(); // #define cellReference _cell.getCellReference() // Remove enclosing quotes if (cellReference[0] == '\"') { stringLibrary::chopLeft(cellReference, 1); stringLibrary::chopRight(cellReference, 1); } // Remove double quotes stringLibrary::replace(cellReference,"\"\"", "\""); // #undef cellReference } in this case, I would replace the variable with the macro to the function. (If I remember correctly I should also use Macros as all caps lock, but I have just left it with the same as the variable name for clarity)
It would be absolutely atrocious to define a macro like what you just showed there: 1. Macros are entities only the preprocessor can see. When you compile your code the file is first passed through the preprocessor and your macro will mean that at every point after that macro definition the word `cellReference` will be replaced by `_cell.getCellReference()`, even outside this function! You can of cause `#undef cellReference` at the last line of the function, but that just adds complexity. Macros don't know scope - they are not C++ code! 2. Your alternative is a reference variable. A reference variable is not required to actually have a place in memory - in your case it will almost surely just be an alias, i.e. the compiler will actually do what you want: it will just replace `cellReference` with `_cell.getReference()` within the scope where `cellReference` is visible. As others said: Macros are almost always a bad idea. If you think "Should I use a macro here?" the answer is in 99.999% of cases "No". Don't use macro unless there is literally NO OTHER WAY. Macros are for doing one thing on Windows and another on Linux, or one thing on x86-64 and another on ARM, or sometimes you can use paramterized macros for code generation in e.g. unit testing frameworks. But that's it. There are proper C++ constructs for all other cases, and they will have no performance penalty.
30
cpp_questions
umbn80
For the wisest among us, what would be the best advice you would say to your loved ones about life?
Well, I don't know if I am "the wisest" of folks, but after 50 years of marriage, raising two kids, being on a job site for 45 years, getting & remaining sober for 18,000+ days, and retiring, becoming a widower, a grandfather, and now being a great-grandfather, my advice to my loved ones is the same as always: Dear Loved Ones: Take good care of your teeth. You will not regret it. You do not have to say everything you think. Sometimes just keeping your mouth shut is a good idea. It costs you nothing to be kind to the people, and the animals, you love. Taking a moment to share a kind word or a smile is time well spent. Don't forget to flirt with your spouse. Just because you have been married for awhile does not mean you need to stop having fun, holding hands, or making out in the car in the driveway. It just means you do it in your own driveway, not your parent's. Treat your life partner well, with love, kindness, and respect, not because of some holiday or anniversary, but because that is how you show your love for the loved ones in your life. Fall down? Get up, brush yourself off, and start again. Repeat as needed. Find a hobby, sport or pasttime that you can do any time you want, and really enjoy it. Let it become a source of pleasure and joy in your life, something you can turn to when you are stressed out, bored, or worried. You will never regret having interests that bring you joy, make you smarter, relax you, or give you the opportunity to meet others. Learn to cook. Hang up the phone. Don't forget to spend time in nature. Move your body every day, out from in front of screens and into the sunshine or the rain. Your physical and mental health will benefit from daily outdoor activities, even if you just walk around the block. Travel when you can, even if it's in your own part of the world. Play music. Fall in love. Life is a gift - open it and do everything. Learn something every day. At 72 years old, I still have lots on my "To Do" list, and I don't let a single day go by without learning something. Hope you all are doing well. Your friend, Herman❤
190
AskOldPeople
umbn80
For the wisest among us, what would be the best advice you would say to your loved ones about life?
It is not even remotely fair. Get over the notion that it will be and you will be better prepared for the crap that will come your way.
50
AskOldPeople
umbn80
For the wisest among us, what would be the best advice you would say to your loved ones about life?
Live it. Do it. Love who you love with reckless abandon and take chances. Travel. Never stop learning. Also, a fucked up brain chemistry can take you down deeper than you know. Be aware not everyone can do what you can. Be patient with small children and old people and pets. Be kind to others and to yourself. You like those flowers? Send some to yourself! Money in the bank is great, but not at the cost of not enjoying the now. Skinny dip at least once. Respect nature. Youth is fleeting and one day you'll wake up and 20 years have passed. If you have a child, know one day you won't know will be the last time you won't be carrying them in your arms. And you won't even be aware, so don't bemoan their dependency on you. One day you'll talk to your parents and end with an "ok,ttyl, love you too" and the next they'll be gone. Tell them now how you remember those little things, promise, they'll remember checking you out of school to go on that picnic too. Don't be unmoving in your opinions, politics, and religion or lack of. Time changes us all. Be the best you ...doesn't matter if you're an astronaut or a vagabond, just give it a decent shot. I miss my parents so much right now. Even though they didn't teach me those things, I learned them anyway and understand their flaws. They probably did the best they could with what they knew or were capable of. Forgive.
30
AskOldPeople
umbwe2
I have as a resource `std::ifstream filestream`, and re-use it for a loop that iterates over filenames: ``` for ( string &filename : filenames ) { filestream.open(filename); sleep(1); //work filestream.close(); } ``` Is my understanding correct: - I believe this introduces a memory leak, if the process exits during the `//work` portion of the code. - One way to solve this is to make filestream a `std::unique_ptr<std::ifstream>`. This works because both the allocated ifstream and the unique_ptr stay in scope, and ifstream remains re-usable for a call to `open()` after `filestream.get().close()` has been closed on it. Also, is this the best way to go about this? (see question title)
Why are you reusing that filestream? For performance? Are you actually resuing it? Calling open() and close() is like constructing and destructing that object, so why not just move it inside the scope of for? Then you'll have a perfectly standard RAII stream.
90
cpp_questions
umbwe2
I have as a resource `std::ifstream filestream`, and re-use it for a loop that iterates over filenames: ``` for ( string &filename : filenames ) { filestream.open(filename); sleep(1); //work filestream.close(); } ``` Is my understanding correct: - I believe this introduces a memory leak, if the process exits during the `//work` portion of the code. - One way to solve this is to make filestream a `std::unique_ptr<std::ifstream>`. This works because both the allocated ifstream and the unique_ptr stay in scope, and ifstream remains re-usable for a call to `open()` after `filestream.get().close()` has been closed on it. Also, is this the best way to go about this? (see question title)
`ifstream` closes in its destructor, it is already a proper RAII type. the code is perfectly fine as it is and changing it will make it much worse. it may make sense to just not reuse it though and make a local `ifstream` inside the loop. if it were a `std::vector`, reusing it is much more beneficial
40
cpp_questions
umbyou
Is there a way to get nex element when using a ranged for loop? For example can you implement a basic bouble sort with 2 for range?
no, you will need to manually loop with index or iterators for sorting
50
cpp_questions
umdbot
I wrote a little bit ago a cmd based program to track my status of series i watch with my girlfriend. The data is saved in a .csv like „Seriesname(char[40]);actualseason(int);actualepisode(int);allseasons(int);allepisodes(int);restepisodes(int)“. The variables are created by a structarray which gets it’s length by the number of lines in the .csv. The program works fine via the command input, but I hate to do everytime the inputline in cmd. I thought about transform my program to winapi, wich i never used before. I get started with a tutorial and kind of understand how it works. I was able to create a button, Textfield and listbox and debug it with a cmd output to see what happens. I implemented the csv read function and i can output everything in cmd. I tried to send the Names via Sendmessage to my listbox, with „(LPARAM)“this is a Name““ I could fill the listbox, but with „(LPARAM)Struct.Seriesname“ it do not work. So it must be the wrong type I think, but I did not find a solution by google it. Is there an easy way to fix this? I can provide my code when I’m at home if needed.
Do yourself a favour, and use a modern UI framework, such as Qt, or WxWidgets instead of fighting with the Windows API.
70
cpp_questions
ume5c8
I feel bad for the horny ppl of the past specifically women https://mobile.twitter.com/broyeanice/status/1443665239132839938
I rather doubt these are real. It’s easy to fake something to look old. Some of the items on the list are not suspect but some of them just sound like what people today think happened back then. Maybe I missed it but I don’t see any sources cited for this. It’s been attributed to McCall’s magazine from 1958. After thinking about it some more, I actually don’t see that many differences between it and what Cosmopolitan magazine suggests. They are equally idiotic. So to be fair, some of those tips are not bad in truth. Get a dog and walk it? I don’t see anything bad there. Even if you don’t catch a husband, you have a nice pet and you’re getting some exercise. Win-win lol.
70
AskOldPeople
ume5c8
I feel bad for the horny ppl of the past specifically women https://mobile.twitter.com/broyeanice/status/1443665239132839938
No first hand experience, but the family history of those days is filled with frustration, forced and failed marriages, judging other family members for seeking happiness, women seen as spinsters at 25, not allowed to educate themselves and forced to stop working when pregnant, partners deemed unfit and other questionable things. And yes, that advice was taken seriously, or at least seen as serious advice. And while some advice was clearly bad and discriminating, some of it was very important. As moving too fast forward with a relationship could easily lead to contracting a disease, becoming pregnant and/or ending up in poverty. As health care and birth control was lacking and poverty was much more common.
60
AskOldPeople
ume5c8
I feel bad for the horny ppl of the past specifically women https://mobile.twitter.com/broyeanice/status/1443665239132839938
People like to read, and so other people crank out shit for them to read. It's better to think of that shit as shit to read, and maybe add some of your own shit if you're reading it in the outhouse, and if you're the type of person who takes that shit seriously, there's a good chance you do use an outhouse. tldr: It's bung-fodder.
50
AskOldPeople
umegcg
Why We won't have to move to RUST?
You don't have to move to Rust, but you can. It's quite nice there: https://en.wikipedia.org/wiki/Rust%2C_Burgenland
40
LearnRust
umg72y
I am working on a system in which some actions are time critical, and other actions have to be executed periodically without particular schedule. I can do a certain number of actions until I need to do the time critical stuff again. This number is not always the same. At the moment I use a loop like this: int actions_allowed, state = 0; while (true){ // Time critical stuff, actions_allowed is calculated here while (actions_allowed-- > 0){ switch (state++){ case 0: // Do stuff... break; case 1: // Do stuff... break; ... case 25: state = 0; //do stuff } } } This is a bit tedious to write. The numbers don't have actual meaning, they just represent an order. If I want to insert something between case 5 and casee 4 I have to change 20 numbers manually. Is there a smarter way to do this? I thought of the way below, is this less efficient as it uses a lot of incrementation and if statements as opposed to a switch statement? while (actions_allowed-- > 0){ int comparator = 0; if (state == comparator++){ // do stuff } else if (state == comparator++){ // do stuff } else if (state == comparator++){ // do stuff ... } else { state = -1; } state++; }
Function pointers are awesome for this sort of thing.
110
cpp_questions
umg72y
I am working on a system in which some actions are time critical, and other actions have to be executed periodically without particular schedule. I can do a certain number of actions until I need to do the time critical stuff again. This number is not always the same. At the moment I use a loop like this: int actions_allowed, state = 0; while (true){ // Time critical stuff, actions_allowed is calculated here while (actions_allowed-- > 0){ switch (state++){ case 0: // Do stuff... break; case 1: // Do stuff... break; ... case 25: state = 0; //do stuff } } } This is a bit tedious to write. The numbers don't have actual meaning, they just represent an order. If I want to insert something between case 5 and casee 4 I have to change 20 numbers manually. Is there a smarter way to do this? I thought of the way below, is this less efficient as it uses a lot of incrementation and if statements as opposed to a switch statement? while (actions_allowed-- > 0){ int comparator = 0; if (state == comparator++){ // do stuff } else if (state == comparator++){ // do stuff } else if (state == comparator++){ // do stuff ... } else { state = -1; } state++; }
How about: static constexpr std::array<void(*)(), 25> actions {&action_0, &action_1, /*...*/, &action_25}; Now you can write a simple algorithm: std::for_each(std::begin(actions), std::next(std::begin(actions), allowed_actions), std::invoke<void()>);
40
cpp_questions
umg72y
I am working on a system in which some actions are time critical, and other actions have to be executed periodically without particular schedule. I can do a certain number of actions until I need to do the time critical stuff again. This number is not always the same. At the moment I use a loop like this: int actions_allowed, state = 0; while (true){ // Time critical stuff, actions_allowed is calculated here while (actions_allowed-- > 0){ switch (state++){ case 0: // Do stuff... break; case 1: // Do stuff... break; ... case 25: state = 0; //do stuff } } } This is a bit tedious to write. The numbers don't have actual meaning, they just represent an order. If I want to insert something between case 5 and casee 4 I have to change 20 numbers manually. Is there a smarter way to do this? I thought of the way below, is this less efficient as it uses a lot of incrementation and if statements as opposed to a switch statement? while (actions_allowed-- > 0){ int comparator = 0; if (state == comparator++){ // do stuff } else if (state == comparator++){ // do stuff } else if (state == comparator++){ // do stuff ... } else { state = -1; } state++; }
You could use an enum to avoid manually shifting the numbers when you want to insert a step into the middle: https://godbolt.org/z/vTrhrMa4M Adding the post_init step in order just means making sure it is in order inside the enum, it doesn't matter where it ends up in the switch (though you should prefer in order there as well.) Be aware the static cast in this example could result in narrowing conversion if you have too many states.
30
cpp_questions