qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
13,537,503
Can I please have a design suggestion for the following problem: I am using Codeigniter/Grocery\_CRUD. My system is multi tenanted - different autonomous sites - within the same client. I have quite a few instances of tables that have unique logical keys. One such table structure is: equip\_items id (pk) equip\_type\_id (fk to equip\_types) site\_id (fk to sites) name Where (equip\_type\_id, site\_id, name) together are a unique key in my db. The issues is that when using a grocery\_CRUD form to add or edit a record that breaks this database rule - the add or edit fails (due to the constraints in the db) but I get no feedback. I need a variation on the is\_unique form\_validation rule by which I can specify the field\*s\* that must be unique. The issues: How to specify the rule? set\_rules() is for a given field and I have multiple fields that the rule will apply to. Does that mean I should abandon the Form\_validation pattern? Or do I follow the 'matches' rule pattern and somehow point to the other fields? Perhaps a callback function would be better but this would mean writing a custom function in each model where I have this problem at last count this is 9 tables. It seems far better to do this in one place (extending form\_validation). Am I missing something already in codeigniter or grocery\_CRUD that has already solved this problem? Any suggestion/advice you might have would be appreciated. **EDIT:** Actually it appears the solution Johnny provided does not quite hit the mark - it enforces each field in unique\_fields() being independently unique - the same as setting is\_unique() on each one. My problem is that in my scenario those fields are a composite unique key (but not the primary key). I don't know if it is significant but further to the original problem statement: 1) site\_id is a 'hidden' field\_type - I don't want my users concerned they are on a different site so I'm dealing with site\_id behind the scenes. 2) Same deal with an equip\_status\_id attribute (not part of the unique key). And 3) I have set\_relations() on all these foreign key attributes and grocery\_CRUD kindly deals with nice drop downs for me. **EDIT 2** I have solved this using a callback.
2012/11/24
[ "https://Stackoverflow.com/questions/13537503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1228116/" ]
**UPDATE:** This code is now part of grocery CRUD version >= 1.4 and you don't need to use an extension anymore. For more see the documentation for [unique\_fields](http://www.grocerycrud.com/documentation/options_functions/unique_fields) I will try to explain it as easy as I can: **1.** First of all for those who have grocery CRUD lower or equal to 1.3.3 has to use this small change: <https://github.com/scoumbourdis/grocery-crud/commit/96ddc991a6ae500ba62303a321be42d75fb82cb2> **2.** Second create a file named grocery\_crud\_extended.php at application/libraries **3.** Copy the below code at your file application/libraries/grocery\_crud\_extended.php ``` <?php class grocery_CRUD_extended extends grocery_CRUD { protected $_unique_fields = array(); public function unique_fields() { $args = func_get_args(); if(isset($args[0]) && is_array($args[0])) { $args = $args[0]; } $this->_unique_fields = $args; return $this; } protected function db_insert_validation() { $validation_result = (object)array('success'=>false); $field_types = $this->get_field_types(); $unique_fields = $this->_unique_fields; $add_fields = $this->get_add_fields(); if(!empty($unique_fields)) { $form_validation = $this->form_validation(); foreach($add_fields as $add_field) { $field_name = $add_field->field_name; if(in_array( $field_name, $unique_fields) ) { $form_validation->set_rules( $field_name, $field_types[$field_name]->display_as, 'is_unique['.$this->basic_db_table.'.'.$field_name.']'); } } if(!$form_validation->run()) { $validation_result->error_message = $form_validation->error_string(); $validation_result->error_fields = $form_validation->_error_array; return $validation_result; } } return parent::db_insert_validation(); } protected function db_update_validation() { $validation_result = (object)array('success'=>false); $field_types = $this->get_field_types(); $unique_fields = $this->_unique_fields; $add_fields = $this->get_add_fields(); if(!empty($unique_fields)) { $form_validation = $this->form_validation(); $form_validation_check = false; foreach($add_fields as $add_field) { $field_name = $add_field->field_name; if(in_array( $field_name, $unique_fields) ) { $state_info = $this->getStateInfo(); $primary_key = $this->get_primary_key(); $field_name_value = $_POST[$field_name]; $ci = &get_instance(); $previous_field_name_value = $ci->db->where($primary_key,$state_info->primary_key) ->get($this->basic_db_table)->row()->$field_name; if(!empty($previous_field_name_value) && $previous_field_name_value != $field_name_value) { $form_validation->set_rules( $field_name, $field_types[$field_name]->display_as, 'is_unique['.$this->basic_db_table.'.'.$field_name.']'); $form_validation_check = true; } } } if($form_validation_check && !$form_validation->run()) { $validation_result->error_message = $form_validation->error_string(); $validation_result->error_fields = $form_validation->_error_array; return $validation_result; } } return parent::db_update_validation(); } } ``` **4.** Now you will simply have to load the grocery\_CRUD\_extended like that: ``` $this->load->library('grocery_CRUD'); $this->load->library('grocery_CRUD_extended'); ``` and then use the: ``` $crud = new grocery_CRUD_extended(); ``` instead of: ``` $crud = new grocery_CRUD(); ``` **5.** Now you can simply have the unique\_fields that it works like this: ``` $crud->unique_fields('field_name1','field_name2','field_name3'); ``` In your case: ``` $crud->unique_fields('equip_type_id','site_id'); ``` Pretty easy right? This is checking if the field is unique or not without actually change the core of grocery CRUD. You can simply use the grocery\_CRUD\_extended instead of grocery\_CRUD and update grocery CRUD library as normal. As I am the author of the library I will try to include this to grocery CRUD version 1.4, so you will not have to use the grocery\_CRUD\_extended in the future.
I have done this using a callback: ``` $crud->set_rules('name','Name','callback_unique_equip_item_check['.$this->uri->segment(4).']'); function unique_equip_item_check($str, $edited_id) { $var = $this->Equip_Item_model->is_unique_except( $edited_id, $this->input->post('site_id'), $this->input->post('equip_type_id'), $this->input->post('name')); if ($var == FALSE) { $s = 'You already have an equipment item of this type with this name.'; $this->form_validation->set_message('unique_equip_item_check', $s); return FALSE; } return TRUE; } ```
16,329
I have some basic questions about my 1-year-old pug. 1. How much should he eat? Typically he should eat 2 times, but he always keeps some food in his bowl and whenever he wants he eats. Is this a good practice? (I use Royal Canin Mini Adult) 2. Now-a-days he always wants what I'm eating. How to stop this? I'm too new (being my first pet) in this area, so your views are appreciated.
2017/02/08
[ "https://pets.stackexchange.com/questions/16329", "https://pets.stackexchange.com", "https://pets.stackexchange.com/users/8839/" ]
1. As Gone2 has stated, you should definitely regulate your pug's intake by removing the food after 15-20 minutes with each feeding. All kibble has feeding directions on the back, so you should follow the feeding recommendations on the bag for his weight unless otherwise directed by a veterinarian. Dogs should generally have a thin layer over their midsection but not so thick you can't feel their ribs. The ribs also shouldn't be visible while they're relaxed. 2. For begging, you can try redirecting by rewarding him when he doesn't beg. Or teach him a down stay. Another method is to give him a toy, himalayan chew, or bully stick to work on while you eat in peace.
1. Leaving food out beyond the two set feeding times is not a good practice. You should go by the recommended amount on the bag for his weight and split that in half; one portion each feeding. 2. To prevent begging you should avoid reacting to the begging and if necessary physically separate yourself from the him while you are eating as most of what we consume can be extremely unhealthy for a dog to consume (salts, sugars, and artificial byproducts they aren't meant to have). Lastly, have you looked into raw feeding?
15,043,674
I do something like this in my code ``` S s; s.a=1 s.b=2 v.push_back(s) ``` Now that C++ has forwarding can i write something like ``` v.push_back(1,2) ``` fyi visual studio supports forwarding as the below works as expected ``` //http://herbsutter.com/gotw/_102/ template<typename T, typename ...Args> std::unique_ptr<T> make_unique( Args&& ...args ) { return std::unique_ptr<T>( new T( std::forward<Args>(args)... ) ); } ```
2013/02/23
[ "https://Stackoverflow.com/questions/15043674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can use `std::vector::emplace_back` which will create the object inplace with the fitting constructor. This of course requires that you have such a constructor defined. ``` v.emplace_back(1,2); ``` As of C++11 every std-container offers an emplace-like function which gives the above described behavior. Compatibility-note: MSVC probably doesn't support this yet as it only supports variadic templates as of the CTP which doesn't affect the standard library and gcc's libstd++ is still missing the emplace member functions in the associative containers.
`push_back` doesn't support forwarding, but the new `emplace_back` does. However, `push_back` does support initializer lists: ``` v.push_back({1,2}); ```
33,840
Consider our world at 18-19 centuries. Our civilization knows how to print books, build steam machines, we have made first experiments on electricity. And one day the [Mad God Sheogorath](http://elderscrolls.wikia.com/wiki/Sheogorath) is emerged. He can bend the reality by his will. For example, he can violate the principles of conservation of energy - build Perpetuum Mobile just to irritate scientists. He can convert Darwin back into the monkey just to help him prove his theory. He can make forgery of dinosaur skeletons, so we have found caterpillar riding tankosaurus instead of diplodocus. He can resurrect people. And, do a lot of things we are not aware. So, in potential he can spoil every scientific acquired experiments result in a way, that is hard to see. So, the question is: is scientific method still possible in this world? UPD: after 20 years Sheogorath have just vanished. Can we undo his trickery and restore science methods?
2016/01/21
[ "https://worldbuilding.stackexchange.com/questions/33840", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/2763/" ]
I think you're vastly underestimating just how different a truly non-deterministic universe would be. **Case A** If the god's influence is sporadic enough that you can still discern a "default" set of laws that nature follows most of the time, then scientists would simply study those laws. **Case B** If the god's influence is *so* omnipresent that you can't discern any underlying patterns at all, then frankly good luck with your story. I don't think the human mind is really capable of imagining a *completely* non-deterministic universe. Everything we take for granted would be gone - things like "objects fall when dropped" and "solid objects can't pass through each other". It's not just that things would have to occasionally behave differently to how we expect them to behave, it's that there could be *no trends whatsoever*. The very notion of causality would be effectively meaningless. And how could life even arise in such a world? In order to justify the existence of humanoid life, you need to assume that on most days, the skeleton can support the muscles, things move when tendons pull them, blood moves when the heart contracts, and so on. But if you assume all that, you're basically already in Case A. You mention, for instance, that he can resurrect people. But the very fact that this is worthy of mention implies that you're assuming dead people still stay dead *most* of the time. So you're already implicitly in Case A. In order to truly be in Case B, you'd need to be assuming that basically, the concept of death doesn't exist, because "life forms tend to die after a while" is already enough of a pattern to place our universe squarely in Case A. In conclusion: either you assume this god's influence is small enough that *yes*, the scientific method would still apply, or you set yourself the task of writing a story taking place in a universe so incomprehensibly different to our own that I'm not sure any human reader will be able to follow the thread of the plot. You'd essentially be writing a work of highly experimental surrealist sci-fi.
This is actually a very common misconception about the scientific method that we seem to teach in schools. The scientific method is not *just* about identifying the "right" laws governing the universe. It is also about building useful models of the universe. In fact, if you are willing to sit down with any real scientist, and use the right philosophical buzz words, you can even get them to admit that they can never provably achieve the former. So let's start to play with some of those philosophical terms! Philosophers call the study of reality "ontology." The word "reality" gets treated many different ways, but intuitively, ontology is looking for what is actually real, not just what appears to be real. Epistemology, on the other hand, is the study of knowledge. Empiricism, a word you may have heard with reference to science, is a branch of epistemology. It studies what we can know through observation of the world around us. The line between these can be seen several ways, but I find the most impressive of them to be the brain-in-a-vat thought experiment. Consider the possibility that you are actually just a brain, sitting in a vat somewhere, being fed neural stimulus like you were part of the Matrix. Ontology would be very interested in the "real world" where you are a brain in a vat, and would call the neural stimulus you are receiving a "simulation." However, just as we saw in the The Matrix, it is remarkably hard to make definitive statements about this reality while you're still jacked into the matrix, and have never observed the outside world. This is the epistomological side: how can one *know* the state of reality? An empirical approach would focus entirely on what can be observed, the stimulus. A 100% empirical scientist would actually not really care whether they are a brain in a vat or not until they identify an observation to defend it (although, in reality, no human is ever 100% anything!) How do we get confused? There are three major categories of thought in logical philosophy. You're almost certainly familiar with deduction and induction. Deduction is going from the general to the specific (all swans are white, so this swan must be white too). Induction is going from the specific to the general (these swans are white, so perhaps all swans are white). There is a third you hear very little about: [abduction](http://plato.stanford.edu/entries/abduction/). Abduction is the ability to infer the best explanation is true. In many discourses, such as science, you end up with many explanations. Maybe your empirical results line up with your theory because your theory is ontologically right, or maybe someone is cleverly massaging the world behind the scenes to fool you. At some point, you may decide the best explanation is that you've found something useful, so you *infer* your theory to be correct. This mode of logic is a fascinating little puzzle because the term "best explanation" leaves so much room for alternatives (read the SEP link above if you're interested). However, any claim of an empirical method, such as science, yielding an ontological truth *must* go through this abductive step. So where does that leave us for the scientific method in the presence of your Mad God Shegorath? Well, from an abductive perspective, the alternative explanations of "Shegorath is just fooling us" starts to become a better explaination, so it becomes harder to use abduction to claim you have arrived at the only worthwhile best possible explanation. You would see additional questioning of scientific results. Enter the Engineer. Engineering and science are tied together intimately, like husband and wife, or perhaps even like conjoined twins. While science provides epistemological ways to "know" things, engineering uses that knowledge to build up the world around us. Of course, science never feeds us perfect knowledge. Only recently did we find out that all of our equations of motions we've been using for a long time get gummed up by relativity. Only recently did we find out that much of the world is non-deterministic thanks to quantum mechanics. Yet what we created from that era is still useful. How? Engineers have a phrase, which I commit to my heart: "All models are wrong, some are useful." We can assume that every model we come up with can be ontologically wrong, because the track record of scientific "knowledge" being revised as new data comes along is 100%. That's not a shortcoming of science, that's actually its strong point: it *always* tries to incorporate the new observations, no matter how undesirable they might be. However, it turns out that for almost everything you or I could want to do, it doesn't have to be perfect. It just has to be close enough to be worth doing. Take teflon, PTFE. Science can develop the molecular structure of PTFE, and say "this is how PTFE works." However, never once will we create a magical perfect PTFE molecule. Every process to make it is slightly flawed. The engineering side is worried about how to use what the science knew about PTFE to coat a non-stick pot. If the science is a *little* wrong, that's okay. We'll do a test run first, to make sure the pots are useful, before selling them! The science is just treated as a guideline -- what really matters is whether the process works or not, not whether it matches exactly the predictions of science. If the science turns out to not be useful for engineering, it will just sit on the shelf until it becomes useful, or dispelled. This is, for example, how we managed to make electronics work for hundreds of years, despite getting the flow of current backwards the entire time. Ben Franklin had to make a guess as to which way the charge was flowing. He guessed wrong, so technically everything we've done with electronics is incorrect. However, his model of electricity was useful enough that there was no need to correct it, until the semiconductor era, where paying attention to what is an electron vs a hole can actually matter. So the scientific method would still be viable in this world with a Mad God. It would simply gravitate towards applications where behaviors are *still* relatively predictable, even after the Mad God. Consider the fact that you're looking at a computer screen right now. If the Mad God were to make the laws of physics too unpredictable, photons would not go in straight lines, and you couldn't read. Of course, it's possible the Mad God decides to only screw with science. He might decide that every science experiment is going to go awry. In this case, he creates all sorts of interesting looping structures as we try to define what a scientific experiment "is." He may actually disappear in a poof of logic, akin to Douglas Adam's god in *Hitchiker's Guide to the Galaxy*! Or he might form a strange loop a. la. Douglas Hofstadter, where he controls the universe, and the universe decides what he will do. If you're going down this path, you're going to have to describe what "viable" means in the question "is the scientific method viable...." If you are presuming an ontological world with such a crazy powerful entity, you are going to have to define your term "viable" in a way which makes sense in their presence. There may also be the question of whether the viability, once defined, can be known by a mere mortal. These questions oft leave philosophers awake at night. As a final fun tidbit, what's to say he hasn't already acted? The ultimate observation, in philosophy, is one done by a being that can think. The ability to do this is called perception. As silly as it may sound, philosophers do not have a clear sense of what perception is, nor how it behaves. Maybe we are just a brain in the jar. Could we perceive it?
33,840
Consider our world at 18-19 centuries. Our civilization knows how to print books, build steam machines, we have made first experiments on electricity. And one day the [Mad God Sheogorath](http://elderscrolls.wikia.com/wiki/Sheogorath) is emerged. He can bend the reality by his will. For example, he can violate the principles of conservation of energy - build Perpetuum Mobile just to irritate scientists. He can convert Darwin back into the monkey just to help him prove his theory. He can make forgery of dinosaur skeletons, so we have found caterpillar riding tankosaurus instead of diplodocus. He can resurrect people. And, do a lot of things we are not aware. So, in potential he can spoil every scientific acquired experiments result in a way, that is hard to see. So, the question is: is scientific method still possible in this world? UPD: after 20 years Sheogorath have just vanished. Can we undo his trickery and restore science methods?
2016/01/21
[ "https://worldbuilding.stackexchange.com/questions/33840", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/2763/" ]
**Caveat**: I've made some assumptions in order to make this work as a potential world. Like many have pointed out, a truly mad god acting without care would probably manage to kill off the human race pretty quickly if they acted often enough to have a tangible effect on the world (by triggering a catastrophic imbalance in the environment). The only way to make this really work as an interesting world would be if Sheogorath was particularly careful in what he did, and only set out to mess with the experiments of scientists and their inventions, and changing the laws of physics/reality over very focused areas, rather than screwing with reality at random. --- Scientific method relies on consistent results, and to a large extent on statistical modelling and probabilities; if I perform 1,000,000 tests of a hypothesis and all come out true, I can say with pretty reasonably probability that it is correct. If Sheogorath's influence is obvious, or at least discernable without *too* much effort (As in, I can tell when something was caused by him rather than being natural), then it would make scientific advancement (or indeed pretty much anything relying on facts) cripplingly slow - I would have to double and triple check every experiment to ensure that no "spoiled" data made it into the calculations, and I'd have to ensure that the calculations themselves weren't spoiled, and every time I read a book I'd have to ensure that the words/results hadn't been changed since they were written down. In other words, everything would take forever. **In this case, scientific method would be possible, but very, very slow**. If his influence is impossible to distinguish from "reality", then all scientific research would be virtually impossible — whenever I get a result, I have no idea whether it's real or Sheogorath is screwing with me. All you could do is note hypotheses and keep as much data as possible, hoping that some day it might be useful. In this case, **Scientific Method would be impossible**. The damage on society is hard to predict. There's a chance that society would fall apart completely depending on whether people are aware that it is the Mad God's doing, or whether they think reality is ending. Then there's the Monotheistic religious crisis, the fact that noone can trust anything they see... theoretically all of civilisation could fall apart if critical things are warped. If he's just messing with science however, and we ignore the other effects on society he would have, then yes, science would recover, probably. 20 years isn't that long a time - people would still be alive that remembered how the methods worked. It's long enough to give up, but not long enough to have forgotten. So long as it is obvious that he is gone, Scientific Method would pick up again. Of course, you'd have to contend with the thought of whether he'd be back. Some people would probably give up saying that there isn't a point, maybe all of them, but I would think that it's likely that at least **SOME** people would take the risk. EDIT: The point of Scientific Study would depend largely on the level of change being effected by Sheogorath: * If major changes were made to reality constantly, society would effectively collapse for those 20 years, if it survived at all. Daily life would be hard enough to predict, let alone finding the time to perform and log scientific experiments. * If minor/minimal changes were made, reality would be deterministic enough that scientific development could probably still be deemed worthwhile. If enough people repeat the experiment, the chances are that eventually there will be enough data to make a probable correct statement. It might be wrong, but it's worth a try... provided Sheogorath doesn't then on a whim decide to make it the opposite just because you've made the discovery. * In an increasing range between the two extremes, Scientific discoveries would be increasingly more unlikely, because everything would be increasingly untrustworthy.
As a writer and reader, if I'm dealing with a being with what we might call "godlike powers", they still have to operate within a larger reality. For example in your setup, Sheogorath builds a tiny "Perpetual Motion Machine" but is actually cheating because in some mysterious god power way, it is perfectly converting a few molecules of MysteriousInvisibleSubstance to Energy at the nano-level. Maybe there's even enough MysteriousInvisibleSubstance to last a thousand years and it's really really hard to detect. MysteriousInvisibleSubstance can also alter visible reality so that Darwin is now stuck in what appears to be a monkey body. Sheogorath can also in some odd way travel in time and use his nifty MysteriousInvisibleSubstance powered MatterReasssembler to screw with the fossils just to screw with the human's of the future's heads. Then Sheogorath disappears. Until the sentients are clever enough to figure out how to detect and then use MysteriousInvisibleSubstance at the molecular level, no "laws of reality" in that fictional world disturbed. That said, for the WorldBuilding exercise to be any fun to read, etc. When the sentients or others of Sheogorath's species figure out what he's been up to and how, Sheogorath is going to be in BIG BIG trouble, right?
33,840
Consider our world at 18-19 centuries. Our civilization knows how to print books, build steam machines, we have made first experiments on electricity. And one day the [Mad God Sheogorath](http://elderscrolls.wikia.com/wiki/Sheogorath) is emerged. He can bend the reality by his will. For example, he can violate the principles of conservation of energy - build Perpetuum Mobile just to irritate scientists. He can convert Darwin back into the monkey just to help him prove his theory. He can make forgery of dinosaur skeletons, so we have found caterpillar riding tankosaurus instead of diplodocus. He can resurrect people. And, do a lot of things we are not aware. So, in potential he can spoil every scientific acquired experiments result in a way, that is hard to see. So, the question is: is scientific method still possible in this world? UPD: after 20 years Sheogorath have just vanished. Can we undo his trickery and restore science methods?
2016/01/21
[ "https://worldbuilding.stackexchange.com/questions/33840", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/2763/" ]
I think you're vastly underestimating just how different a truly non-deterministic universe would be. **Case A** If the god's influence is sporadic enough that you can still discern a "default" set of laws that nature follows most of the time, then scientists would simply study those laws. **Case B** If the god's influence is *so* omnipresent that you can't discern any underlying patterns at all, then frankly good luck with your story. I don't think the human mind is really capable of imagining a *completely* non-deterministic universe. Everything we take for granted would be gone - things like "objects fall when dropped" and "solid objects can't pass through each other". It's not just that things would have to occasionally behave differently to how we expect them to behave, it's that there could be *no trends whatsoever*. The very notion of causality would be effectively meaningless. And how could life even arise in such a world? In order to justify the existence of humanoid life, you need to assume that on most days, the skeleton can support the muscles, things move when tendons pull them, blood moves when the heart contracts, and so on. But if you assume all that, you're basically already in Case A. You mention, for instance, that he can resurrect people. But the very fact that this is worthy of mention implies that you're assuming dead people still stay dead *most* of the time. So you're already implicitly in Case A. In order to truly be in Case B, you'd need to be assuming that basically, the concept of death doesn't exist, because "life forms tend to die after a while" is already enough of a pattern to place our universe squarely in Case A. In conclusion: either you assume this god's influence is small enough that *yes*, the scientific method would still apply, or you set yourself the task of writing a story taking place in a universe so incomprehensibly different to our own that I'm not sure any human reader will be able to follow the thread of the plot. You'd essentially be writing a work of highly experimental surrealist sci-fi.
As a writer and reader, if I'm dealing with a being with what we might call "godlike powers", they still have to operate within a larger reality. For example in your setup, Sheogorath builds a tiny "Perpetual Motion Machine" but is actually cheating because in some mysterious god power way, it is perfectly converting a few molecules of MysteriousInvisibleSubstance to Energy at the nano-level. Maybe there's even enough MysteriousInvisibleSubstance to last a thousand years and it's really really hard to detect. MysteriousInvisibleSubstance can also alter visible reality so that Darwin is now stuck in what appears to be a monkey body. Sheogorath can also in some odd way travel in time and use his nifty MysteriousInvisibleSubstance powered MatterReasssembler to screw with the fossils just to screw with the human's of the future's heads. Then Sheogorath disappears. Until the sentients are clever enough to figure out how to detect and then use MysteriousInvisibleSubstance at the molecular level, no "laws of reality" in that fictional world disturbed. That said, for the WorldBuilding exercise to be any fun to read, etc. When the sentients or others of Sheogorath's species figure out what he's been up to and how, Sheogorath is going to be in BIG BIG trouble, right?
33,840
Consider our world at 18-19 centuries. Our civilization knows how to print books, build steam machines, we have made first experiments on electricity. And one day the [Mad God Sheogorath](http://elderscrolls.wikia.com/wiki/Sheogorath) is emerged. He can bend the reality by his will. For example, he can violate the principles of conservation of energy - build Perpetuum Mobile just to irritate scientists. He can convert Darwin back into the monkey just to help him prove his theory. He can make forgery of dinosaur skeletons, so we have found caterpillar riding tankosaurus instead of diplodocus. He can resurrect people. And, do a lot of things we are not aware. So, in potential he can spoil every scientific acquired experiments result in a way, that is hard to see. So, the question is: is scientific method still possible in this world? UPD: after 20 years Sheogorath have just vanished. Can we undo his trickery and restore science methods?
2016/01/21
[ "https://worldbuilding.stackexchange.com/questions/33840", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/2763/" ]
**It very much depends on your god's sense of humour.** If he's decided for example that [da red wunz go fasta](https://en.wikipedia.org/wiki/Ork_%28Warhammer_40,000%29) and anything blue can fly then you've pretty much had it. All the rules that you come up with are going to be wrong. If his logic has an internal consistency and lasting effect even after he's gone, messing with the fossil records etc, then the damage is done and you can never get a right and proper answer. If there's no consistency and he's just randomly poking experiments and giggling then it's all about spotting and excluding the results that don't fit. If on the other hand, the red ones continue to go faster even after he's gone and you can ignore aerodynamic lift and just paint it blue instead, perhaps the scientific method remains valid. You just won't get the answers that maybe you did before he came along.
This is actually a very common misconception about the scientific method that we seem to teach in schools. The scientific method is not *just* about identifying the "right" laws governing the universe. It is also about building useful models of the universe. In fact, if you are willing to sit down with any real scientist, and use the right philosophical buzz words, you can even get them to admit that they can never provably achieve the former. So let's start to play with some of those philosophical terms! Philosophers call the study of reality "ontology." The word "reality" gets treated many different ways, but intuitively, ontology is looking for what is actually real, not just what appears to be real. Epistemology, on the other hand, is the study of knowledge. Empiricism, a word you may have heard with reference to science, is a branch of epistemology. It studies what we can know through observation of the world around us. The line between these can be seen several ways, but I find the most impressive of them to be the brain-in-a-vat thought experiment. Consider the possibility that you are actually just a brain, sitting in a vat somewhere, being fed neural stimulus like you were part of the Matrix. Ontology would be very interested in the "real world" where you are a brain in a vat, and would call the neural stimulus you are receiving a "simulation." However, just as we saw in the The Matrix, it is remarkably hard to make definitive statements about this reality while you're still jacked into the matrix, and have never observed the outside world. This is the epistomological side: how can one *know* the state of reality? An empirical approach would focus entirely on what can be observed, the stimulus. A 100% empirical scientist would actually not really care whether they are a brain in a vat or not until they identify an observation to defend it (although, in reality, no human is ever 100% anything!) How do we get confused? There are three major categories of thought in logical philosophy. You're almost certainly familiar with deduction and induction. Deduction is going from the general to the specific (all swans are white, so this swan must be white too). Induction is going from the specific to the general (these swans are white, so perhaps all swans are white). There is a third you hear very little about: [abduction](http://plato.stanford.edu/entries/abduction/). Abduction is the ability to infer the best explanation is true. In many discourses, such as science, you end up with many explanations. Maybe your empirical results line up with your theory because your theory is ontologically right, or maybe someone is cleverly massaging the world behind the scenes to fool you. At some point, you may decide the best explanation is that you've found something useful, so you *infer* your theory to be correct. This mode of logic is a fascinating little puzzle because the term "best explanation" leaves so much room for alternatives (read the SEP link above if you're interested). However, any claim of an empirical method, such as science, yielding an ontological truth *must* go through this abductive step. So where does that leave us for the scientific method in the presence of your Mad God Shegorath? Well, from an abductive perspective, the alternative explanations of "Shegorath is just fooling us" starts to become a better explaination, so it becomes harder to use abduction to claim you have arrived at the only worthwhile best possible explanation. You would see additional questioning of scientific results. Enter the Engineer. Engineering and science are tied together intimately, like husband and wife, or perhaps even like conjoined twins. While science provides epistemological ways to "know" things, engineering uses that knowledge to build up the world around us. Of course, science never feeds us perfect knowledge. Only recently did we find out that all of our equations of motions we've been using for a long time get gummed up by relativity. Only recently did we find out that much of the world is non-deterministic thanks to quantum mechanics. Yet what we created from that era is still useful. How? Engineers have a phrase, which I commit to my heart: "All models are wrong, some are useful." We can assume that every model we come up with can be ontologically wrong, because the track record of scientific "knowledge" being revised as new data comes along is 100%. That's not a shortcoming of science, that's actually its strong point: it *always* tries to incorporate the new observations, no matter how undesirable they might be. However, it turns out that for almost everything you or I could want to do, it doesn't have to be perfect. It just has to be close enough to be worth doing. Take teflon, PTFE. Science can develop the molecular structure of PTFE, and say "this is how PTFE works." However, never once will we create a magical perfect PTFE molecule. Every process to make it is slightly flawed. The engineering side is worried about how to use what the science knew about PTFE to coat a non-stick pot. If the science is a *little* wrong, that's okay. We'll do a test run first, to make sure the pots are useful, before selling them! The science is just treated as a guideline -- what really matters is whether the process works or not, not whether it matches exactly the predictions of science. If the science turns out to not be useful for engineering, it will just sit on the shelf until it becomes useful, or dispelled. This is, for example, how we managed to make electronics work for hundreds of years, despite getting the flow of current backwards the entire time. Ben Franklin had to make a guess as to which way the charge was flowing. He guessed wrong, so technically everything we've done with electronics is incorrect. However, his model of electricity was useful enough that there was no need to correct it, until the semiconductor era, where paying attention to what is an electron vs a hole can actually matter. So the scientific method would still be viable in this world with a Mad God. It would simply gravitate towards applications where behaviors are *still* relatively predictable, even after the Mad God. Consider the fact that you're looking at a computer screen right now. If the Mad God were to make the laws of physics too unpredictable, photons would not go in straight lines, and you couldn't read. Of course, it's possible the Mad God decides to only screw with science. He might decide that every science experiment is going to go awry. In this case, he creates all sorts of interesting looping structures as we try to define what a scientific experiment "is." He may actually disappear in a poof of logic, akin to Douglas Adam's god in *Hitchiker's Guide to the Galaxy*! Or he might form a strange loop a. la. Douglas Hofstadter, where he controls the universe, and the universe decides what he will do. If you're going down this path, you're going to have to describe what "viable" means in the question "is the scientific method viable...." If you are presuming an ontological world with such a crazy powerful entity, you are going to have to define your term "viable" in a way which makes sense in their presence. There may also be the question of whether the viability, once defined, can be known by a mere mortal. These questions oft leave philosophers awake at night. As a final fun tidbit, what's to say he hasn't already acted? The ultimate observation, in philosophy, is one done by a being that can think. The ability to do this is called perception. As silly as it may sound, philosophers do not have a clear sense of what perception is, nor how it behaves. Maybe we are just a brain in the jar. Could we perceive it?
33,840
Consider our world at 18-19 centuries. Our civilization knows how to print books, build steam machines, we have made first experiments on electricity. And one day the [Mad God Sheogorath](http://elderscrolls.wikia.com/wiki/Sheogorath) is emerged. He can bend the reality by his will. For example, he can violate the principles of conservation of energy - build Perpetuum Mobile just to irritate scientists. He can convert Darwin back into the monkey just to help him prove his theory. He can make forgery of dinosaur skeletons, so we have found caterpillar riding tankosaurus instead of diplodocus. He can resurrect people. And, do a lot of things we are not aware. So, in potential he can spoil every scientific acquired experiments result in a way, that is hard to see. So, the question is: is scientific method still possible in this world? UPD: after 20 years Sheogorath have just vanished. Can we undo his trickery and restore science methods?
2016/01/21
[ "https://worldbuilding.stackexchange.com/questions/33840", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/2763/" ]
**Absolutely** To quote some mouseover text from a certain webcomic: 'We don't use science to prove we're right. We use science to *become* right'. The scientific method is just as valid in your crazy mixed up world as it is now, and will remain so unless the world becomes so crazy that no logical sense can be made of it *at all*. This is because science *isn't* something that we use to show a particular result, it's the way we can explore the world around us. If, suddenly, the rules don't seem to apply because a mad god is messing with us, then the scientific method can still be used to tell us whether or not there is something messing with us. Then it can be used to explore the limits of this entity, and even it's psychology. This then forms a new paradigm of the world, and new theories start to form around that, bolstered by the scientific explorations mankind is making into the nature of our environment *with the mad god in it*. The only way in which this doesn't work is if the mad god is randomly changing everything, all the time, to the point where everything that humanity could possibly know breaks down. At that point it's a somewhat moot point, because the universe will have become a tumultuous maelstrom summoned from the fever dreams of a crazed god. As an example: The mad god has decided to break all experiments that require electrical measurements. Scientists notice that while all their lab equipment is broken, the lights are still on. A simple experiment therefore becomes: when I turn the light switch: do the lights turn on and off? My hypothesis is that the light switch controls the flow of electricity to the light. Now the mad god has a choice. Either the lights continue to work as normal (hooray, the scientific method worked!) or he chooses to change how lightswitches work. If he goes for completely random on-off for lights and light switches, either *the world now works in a different way*, namely, nobody can control the lights, or it's just our scientists that are affected. Either way we then know more about the world around us, either something powerful is messing about with rigorous scientific experiments, or that lights now turn on and off at random, and nothing can stop it. TL:DR: The scientific method is used to figure out how the world works. If the way the world works is that we're captive to the whim of a god who doesn't like science, that's what we'll find out using it. From that point on it's one for the theopsychologists.
As a writer and reader, if I'm dealing with a being with what we might call "godlike powers", they still have to operate within a larger reality. For example in your setup, Sheogorath builds a tiny "Perpetual Motion Machine" but is actually cheating because in some mysterious god power way, it is perfectly converting a few molecules of MysteriousInvisibleSubstance to Energy at the nano-level. Maybe there's even enough MysteriousInvisibleSubstance to last a thousand years and it's really really hard to detect. MysteriousInvisibleSubstance can also alter visible reality so that Darwin is now stuck in what appears to be a monkey body. Sheogorath can also in some odd way travel in time and use his nifty MysteriousInvisibleSubstance powered MatterReasssembler to screw with the fossils just to screw with the human's of the future's heads. Then Sheogorath disappears. Until the sentients are clever enough to figure out how to detect and then use MysteriousInvisibleSubstance at the molecular level, no "laws of reality" in that fictional world disturbed. That said, for the WorldBuilding exercise to be any fun to read, etc. When the sentients or others of Sheogorath's species figure out what he's been up to and how, Sheogorath is going to be in BIG BIG trouble, right?
33,840
Consider our world at 18-19 centuries. Our civilization knows how to print books, build steam machines, we have made first experiments on electricity. And one day the [Mad God Sheogorath](http://elderscrolls.wikia.com/wiki/Sheogorath) is emerged. He can bend the reality by his will. For example, he can violate the principles of conservation of energy - build Perpetuum Mobile just to irritate scientists. He can convert Darwin back into the monkey just to help him prove his theory. He can make forgery of dinosaur skeletons, so we have found caterpillar riding tankosaurus instead of diplodocus. He can resurrect people. And, do a lot of things we are not aware. So, in potential he can spoil every scientific acquired experiments result in a way, that is hard to see. So, the question is: is scientific method still possible in this world? UPD: after 20 years Sheogorath have just vanished. Can we undo his trickery and restore science methods?
2016/01/21
[ "https://worldbuilding.stackexchange.com/questions/33840", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/2763/" ]
**Caveat**: I've made some assumptions in order to make this work as a potential world. Like many have pointed out, a truly mad god acting without care would probably manage to kill off the human race pretty quickly if they acted often enough to have a tangible effect on the world (by triggering a catastrophic imbalance in the environment). The only way to make this really work as an interesting world would be if Sheogorath was particularly careful in what he did, and only set out to mess with the experiments of scientists and their inventions, and changing the laws of physics/reality over very focused areas, rather than screwing with reality at random. --- Scientific method relies on consistent results, and to a large extent on statistical modelling and probabilities; if I perform 1,000,000 tests of a hypothesis and all come out true, I can say with pretty reasonably probability that it is correct. If Sheogorath's influence is obvious, or at least discernable without *too* much effort (As in, I can tell when something was caused by him rather than being natural), then it would make scientific advancement (or indeed pretty much anything relying on facts) cripplingly slow - I would have to double and triple check every experiment to ensure that no "spoiled" data made it into the calculations, and I'd have to ensure that the calculations themselves weren't spoiled, and every time I read a book I'd have to ensure that the words/results hadn't been changed since they were written down. In other words, everything would take forever. **In this case, scientific method would be possible, but very, very slow**. If his influence is impossible to distinguish from "reality", then all scientific research would be virtually impossible — whenever I get a result, I have no idea whether it's real or Sheogorath is screwing with me. All you could do is note hypotheses and keep as much data as possible, hoping that some day it might be useful. In this case, **Scientific Method would be impossible**. The damage on society is hard to predict. There's a chance that society would fall apart completely depending on whether people are aware that it is the Mad God's doing, or whether they think reality is ending. Then there's the Monotheistic religious crisis, the fact that noone can trust anything they see... theoretically all of civilisation could fall apart if critical things are warped. If he's just messing with science however, and we ignore the other effects on society he would have, then yes, science would recover, probably. 20 years isn't that long a time - people would still be alive that remembered how the methods worked. It's long enough to give up, but not long enough to have forgotten. So long as it is obvious that he is gone, Scientific Method would pick up again. Of course, you'd have to contend with the thought of whether he'd be back. Some people would probably give up saying that there isn't a point, maybe all of them, but I would think that it's likely that at least **SOME** people would take the risk. EDIT: The point of Scientific Study would depend largely on the level of change being effected by Sheogorath: * If major changes were made to reality constantly, society would effectively collapse for those 20 years, if it survived at all. Daily life would be hard enough to predict, let alone finding the time to perform and log scientific experiments. * If minor/minimal changes were made, reality would be deterministic enough that scientific development could probably still be deemed worthwhile. If enough people repeat the experiment, the chances are that eventually there will be enough data to make a probable correct statement. It might be wrong, but it's worth a try... provided Sheogorath doesn't then on a whim decide to make it the opposite just because you've made the discovery. * In an increasing range between the two extremes, Scientific discoveries would be increasingly more unlikely, because everything would be increasingly untrustworthy.
**Absolutely** To quote some mouseover text from a certain webcomic: 'We don't use science to prove we're right. We use science to *become* right'. The scientific method is just as valid in your crazy mixed up world as it is now, and will remain so unless the world becomes so crazy that no logical sense can be made of it *at all*. This is because science *isn't* something that we use to show a particular result, it's the way we can explore the world around us. If, suddenly, the rules don't seem to apply because a mad god is messing with us, then the scientific method can still be used to tell us whether or not there is something messing with us. Then it can be used to explore the limits of this entity, and even it's psychology. This then forms a new paradigm of the world, and new theories start to form around that, bolstered by the scientific explorations mankind is making into the nature of our environment *with the mad god in it*. The only way in which this doesn't work is if the mad god is randomly changing everything, all the time, to the point where everything that humanity could possibly know breaks down. At that point it's a somewhat moot point, because the universe will have become a tumultuous maelstrom summoned from the fever dreams of a crazed god. As an example: The mad god has decided to break all experiments that require electrical measurements. Scientists notice that while all their lab equipment is broken, the lights are still on. A simple experiment therefore becomes: when I turn the light switch: do the lights turn on and off? My hypothesis is that the light switch controls the flow of electricity to the light. Now the mad god has a choice. Either the lights continue to work as normal (hooray, the scientific method worked!) or he chooses to change how lightswitches work. If he goes for completely random on-off for lights and light switches, either *the world now works in a different way*, namely, nobody can control the lights, or it's just our scientists that are affected. Either way we then know more about the world around us, either something powerful is messing about with rigorous scientific experiments, or that lights now turn on and off at random, and nothing can stop it. TL:DR: The scientific method is used to figure out how the world works. If the way the world works is that we're captive to the whim of a god who doesn't like science, that's what we'll find out using it. From that point on it's one for the theopsychologists.
33,840
Consider our world at 18-19 centuries. Our civilization knows how to print books, build steam machines, we have made first experiments on electricity. And one day the [Mad God Sheogorath](http://elderscrolls.wikia.com/wiki/Sheogorath) is emerged. He can bend the reality by his will. For example, he can violate the principles of conservation of energy - build Perpetuum Mobile just to irritate scientists. He can convert Darwin back into the monkey just to help him prove his theory. He can make forgery of dinosaur skeletons, so we have found caterpillar riding tankosaurus instead of diplodocus. He can resurrect people. And, do a lot of things we are not aware. So, in potential he can spoil every scientific acquired experiments result in a way, that is hard to see. So, the question is: is scientific method still possible in this world? UPD: after 20 years Sheogorath have just vanished. Can we undo his trickery and restore science methods?
2016/01/21
[ "https://worldbuilding.stackexchange.com/questions/33840", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/2763/" ]
*Is the scientific method still possible in this world?* More or less. The scientific method depends heavily on being able to prove things are either true or false (at least it used to) with as many few "maybe" in between as possible. Those "maybe" being mostly regarded as proof of falsehood. Simply put, it depends on what has the Mad God touched. If all it does is punctually changing one thing, then scientific method can still be applied to everything else, with the warning that this all powerful being can have messed with it for fun and giggles. So the scientific method would take exceptions into account and distrusts single fact as proof - one way of another - even more than today. The problem would come if the mad god changed some fundamental things so that they permanently gave random results. If she made it so that light passing through a prism changed color randomly, all science related to this particular field would be devastated. *After 20 years Sheogorath have just vanished. Can we undo his trickery and restore scientific methods?* It depend directly on the permanence of the effects : killing zombies, deciding that once occurring tankosaurus are proof of nothing is easy. Restoring laws of physics bent by the will of a god is another matter. *A short conclusion :* All in all it could be regarded as pranks from a couple ten year old mischievous, all powerful kids. Fear and annoyment would be the main feelings toward the results. Oh, and hate of those responsible. If it's linked to a scientific group, then the whole scientific community could be seen as responsible, thus creating a huge problem.
As a writer and reader, if I'm dealing with a being with what we might call "godlike powers", they still have to operate within a larger reality. For example in your setup, Sheogorath builds a tiny "Perpetual Motion Machine" but is actually cheating because in some mysterious god power way, it is perfectly converting a few molecules of MysteriousInvisibleSubstance to Energy at the nano-level. Maybe there's even enough MysteriousInvisibleSubstance to last a thousand years and it's really really hard to detect. MysteriousInvisibleSubstance can also alter visible reality so that Darwin is now stuck in what appears to be a monkey body. Sheogorath can also in some odd way travel in time and use his nifty MysteriousInvisibleSubstance powered MatterReasssembler to screw with the fossils just to screw with the human's of the future's heads. Then Sheogorath disappears. Until the sentients are clever enough to figure out how to detect and then use MysteriousInvisibleSubstance at the molecular level, no "laws of reality" in that fictional world disturbed. That said, for the WorldBuilding exercise to be any fun to read, etc. When the sentients or others of Sheogorath's species figure out what he's been up to and how, Sheogorath is going to be in BIG BIG trouble, right?
33,840
Consider our world at 18-19 centuries. Our civilization knows how to print books, build steam machines, we have made first experiments on electricity. And one day the [Mad God Sheogorath](http://elderscrolls.wikia.com/wiki/Sheogorath) is emerged. He can bend the reality by his will. For example, he can violate the principles of conservation of energy - build Perpetuum Mobile just to irritate scientists. He can convert Darwin back into the monkey just to help him prove his theory. He can make forgery of dinosaur skeletons, so we have found caterpillar riding tankosaurus instead of diplodocus. He can resurrect people. And, do a lot of things we are not aware. So, in potential he can spoil every scientific acquired experiments result in a way, that is hard to see. So, the question is: is scientific method still possible in this world? UPD: after 20 years Sheogorath have just vanished. Can we undo his trickery and restore science methods?
2016/01/21
[ "https://worldbuilding.stackexchange.com/questions/33840", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/2763/" ]
**Caveat**: I've made some assumptions in order to make this work as a potential world. Like many have pointed out, a truly mad god acting without care would probably manage to kill off the human race pretty quickly if they acted often enough to have a tangible effect on the world (by triggering a catastrophic imbalance in the environment). The only way to make this really work as an interesting world would be if Sheogorath was particularly careful in what he did, and only set out to mess with the experiments of scientists and their inventions, and changing the laws of physics/reality over very focused areas, rather than screwing with reality at random. --- Scientific method relies on consistent results, and to a large extent on statistical modelling and probabilities; if I perform 1,000,000 tests of a hypothesis and all come out true, I can say with pretty reasonably probability that it is correct. If Sheogorath's influence is obvious, or at least discernable without *too* much effort (As in, I can tell when something was caused by him rather than being natural), then it would make scientific advancement (or indeed pretty much anything relying on facts) cripplingly slow - I would have to double and triple check every experiment to ensure that no "spoiled" data made it into the calculations, and I'd have to ensure that the calculations themselves weren't spoiled, and every time I read a book I'd have to ensure that the words/results hadn't been changed since they were written down. In other words, everything would take forever. **In this case, scientific method would be possible, but very, very slow**. If his influence is impossible to distinguish from "reality", then all scientific research would be virtually impossible — whenever I get a result, I have no idea whether it's real or Sheogorath is screwing with me. All you could do is note hypotheses and keep as much data as possible, hoping that some day it might be useful. In this case, **Scientific Method would be impossible**. The damage on society is hard to predict. There's a chance that society would fall apart completely depending on whether people are aware that it is the Mad God's doing, or whether they think reality is ending. Then there's the Monotheistic religious crisis, the fact that noone can trust anything they see... theoretically all of civilisation could fall apart if critical things are warped. If he's just messing with science however, and we ignore the other effects on society he would have, then yes, science would recover, probably. 20 years isn't that long a time - people would still be alive that remembered how the methods worked. It's long enough to give up, but not long enough to have forgotten. So long as it is obvious that he is gone, Scientific Method would pick up again. Of course, you'd have to contend with the thought of whether he'd be back. Some people would probably give up saying that there isn't a point, maybe all of them, but I would think that it's likely that at least **SOME** people would take the risk. EDIT: The point of Scientific Study would depend largely on the level of change being effected by Sheogorath: * If major changes were made to reality constantly, society would effectively collapse for those 20 years, if it survived at all. Daily life would be hard enough to predict, let alone finding the time to perform and log scientific experiments. * If minor/minimal changes were made, reality would be deterministic enough that scientific development could probably still be deemed worthwhile. If enough people repeat the experiment, the chances are that eventually there will be enough data to make a probable correct statement. It might be wrong, but it's worth a try... provided Sheogorath doesn't then on a whim decide to make it the opposite just because you've made the discovery. * In an increasing range between the two extremes, Scientific discoveries would be increasingly more unlikely, because everything would be increasingly untrustworthy.
This is actually a very common misconception about the scientific method that we seem to teach in schools. The scientific method is not *just* about identifying the "right" laws governing the universe. It is also about building useful models of the universe. In fact, if you are willing to sit down with any real scientist, and use the right philosophical buzz words, you can even get them to admit that they can never provably achieve the former. So let's start to play with some of those philosophical terms! Philosophers call the study of reality "ontology." The word "reality" gets treated many different ways, but intuitively, ontology is looking for what is actually real, not just what appears to be real. Epistemology, on the other hand, is the study of knowledge. Empiricism, a word you may have heard with reference to science, is a branch of epistemology. It studies what we can know through observation of the world around us. The line between these can be seen several ways, but I find the most impressive of them to be the brain-in-a-vat thought experiment. Consider the possibility that you are actually just a brain, sitting in a vat somewhere, being fed neural stimulus like you were part of the Matrix. Ontology would be very interested in the "real world" where you are a brain in a vat, and would call the neural stimulus you are receiving a "simulation." However, just as we saw in the The Matrix, it is remarkably hard to make definitive statements about this reality while you're still jacked into the matrix, and have never observed the outside world. This is the epistomological side: how can one *know* the state of reality? An empirical approach would focus entirely on what can be observed, the stimulus. A 100% empirical scientist would actually not really care whether they are a brain in a vat or not until they identify an observation to defend it (although, in reality, no human is ever 100% anything!) How do we get confused? There are three major categories of thought in logical philosophy. You're almost certainly familiar with deduction and induction. Deduction is going from the general to the specific (all swans are white, so this swan must be white too). Induction is going from the specific to the general (these swans are white, so perhaps all swans are white). There is a third you hear very little about: [abduction](http://plato.stanford.edu/entries/abduction/). Abduction is the ability to infer the best explanation is true. In many discourses, such as science, you end up with many explanations. Maybe your empirical results line up with your theory because your theory is ontologically right, or maybe someone is cleverly massaging the world behind the scenes to fool you. At some point, you may decide the best explanation is that you've found something useful, so you *infer* your theory to be correct. This mode of logic is a fascinating little puzzle because the term "best explanation" leaves so much room for alternatives (read the SEP link above if you're interested). However, any claim of an empirical method, such as science, yielding an ontological truth *must* go through this abductive step. So where does that leave us for the scientific method in the presence of your Mad God Shegorath? Well, from an abductive perspective, the alternative explanations of "Shegorath is just fooling us" starts to become a better explaination, so it becomes harder to use abduction to claim you have arrived at the only worthwhile best possible explanation. You would see additional questioning of scientific results. Enter the Engineer. Engineering and science are tied together intimately, like husband and wife, or perhaps even like conjoined twins. While science provides epistemological ways to "know" things, engineering uses that knowledge to build up the world around us. Of course, science never feeds us perfect knowledge. Only recently did we find out that all of our equations of motions we've been using for a long time get gummed up by relativity. Only recently did we find out that much of the world is non-deterministic thanks to quantum mechanics. Yet what we created from that era is still useful. How? Engineers have a phrase, which I commit to my heart: "All models are wrong, some are useful." We can assume that every model we come up with can be ontologically wrong, because the track record of scientific "knowledge" being revised as new data comes along is 100%. That's not a shortcoming of science, that's actually its strong point: it *always* tries to incorporate the new observations, no matter how undesirable they might be. However, it turns out that for almost everything you or I could want to do, it doesn't have to be perfect. It just has to be close enough to be worth doing. Take teflon, PTFE. Science can develop the molecular structure of PTFE, and say "this is how PTFE works." However, never once will we create a magical perfect PTFE molecule. Every process to make it is slightly flawed. The engineering side is worried about how to use what the science knew about PTFE to coat a non-stick pot. If the science is a *little* wrong, that's okay. We'll do a test run first, to make sure the pots are useful, before selling them! The science is just treated as a guideline -- what really matters is whether the process works or not, not whether it matches exactly the predictions of science. If the science turns out to not be useful for engineering, it will just sit on the shelf until it becomes useful, or dispelled. This is, for example, how we managed to make electronics work for hundreds of years, despite getting the flow of current backwards the entire time. Ben Franklin had to make a guess as to which way the charge was flowing. He guessed wrong, so technically everything we've done with electronics is incorrect. However, his model of electricity was useful enough that there was no need to correct it, until the semiconductor era, where paying attention to what is an electron vs a hole can actually matter. So the scientific method would still be viable in this world with a Mad God. It would simply gravitate towards applications where behaviors are *still* relatively predictable, even after the Mad God. Consider the fact that you're looking at a computer screen right now. If the Mad God were to make the laws of physics too unpredictable, photons would not go in straight lines, and you couldn't read. Of course, it's possible the Mad God decides to only screw with science. He might decide that every science experiment is going to go awry. In this case, he creates all sorts of interesting looping structures as we try to define what a scientific experiment "is." He may actually disappear in a poof of logic, akin to Douglas Adam's god in *Hitchiker's Guide to the Galaxy*! Or he might form a strange loop a. la. Douglas Hofstadter, where he controls the universe, and the universe decides what he will do. If you're going down this path, you're going to have to describe what "viable" means in the question "is the scientific method viable...." If you are presuming an ontological world with such a crazy powerful entity, you are going to have to define your term "viable" in a way which makes sense in their presence. There may also be the question of whether the viability, once defined, can be known by a mere mortal. These questions oft leave philosophers awake at night. As a final fun tidbit, what's to say he hasn't already acted? The ultimate observation, in philosophy, is one done by a being that can think. The ability to do this is called perception. As silly as it may sound, philosophers do not have a clear sense of what perception is, nor how it behaves. Maybe we are just a brain in the jar. Could we perceive it?
33,840
Consider our world at 18-19 centuries. Our civilization knows how to print books, build steam machines, we have made first experiments on electricity. And one day the [Mad God Sheogorath](http://elderscrolls.wikia.com/wiki/Sheogorath) is emerged. He can bend the reality by his will. For example, he can violate the principles of conservation of energy - build Perpetuum Mobile just to irritate scientists. He can convert Darwin back into the monkey just to help him prove his theory. He can make forgery of dinosaur skeletons, so we have found caterpillar riding tankosaurus instead of diplodocus. He can resurrect people. And, do a lot of things we are not aware. So, in potential he can spoil every scientific acquired experiments result in a way, that is hard to see. So, the question is: is scientific method still possible in this world? UPD: after 20 years Sheogorath have just vanished. Can we undo his trickery and restore science methods?
2016/01/21
[ "https://worldbuilding.stackexchange.com/questions/33840", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/2763/" ]
**It very much depends on your god's sense of humour.** If he's decided for example that [da red wunz go fasta](https://en.wikipedia.org/wiki/Ork_%28Warhammer_40,000%29) and anything blue can fly then you've pretty much had it. All the rules that you come up with are going to be wrong. If his logic has an internal consistency and lasting effect even after he's gone, messing with the fossil records etc, then the damage is done and you can never get a right and proper answer. If there's no consistency and he's just randomly poking experiments and giggling then it's all about spotting and excluding the results that don't fit. If on the other hand, the red ones continue to go faster even after he's gone and you can ignore aerodynamic lift and just paint it blue instead, perhaps the scientific method remains valid. You just won't get the answers that maybe you did before he came along.
As a writer and reader, if I'm dealing with a being with what we might call "godlike powers", they still have to operate within a larger reality. For example in your setup, Sheogorath builds a tiny "Perpetual Motion Machine" but is actually cheating because in some mysterious god power way, it is perfectly converting a few molecules of MysteriousInvisibleSubstance to Energy at the nano-level. Maybe there's even enough MysteriousInvisibleSubstance to last a thousand years and it's really really hard to detect. MysteriousInvisibleSubstance can also alter visible reality so that Darwin is now stuck in what appears to be a monkey body. Sheogorath can also in some odd way travel in time and use his nifty MysteriousInvisibleSubstance powered MatterReasssembler to screw with the fossils just to screw with the human's of the future's heads. Then Sheogorath disappears. Until the sentients are clever enough to figure out how to detect and then use MysteriousInvisibleSubstance at the molecular level, no "laws of reality" in that fictional world disturbed. That said, for the WorldBuilding exercise to be any fun to read, etc. When the sentients or others of Sheogorath's species figure out what he's been up to and how, Sheogorath is going to be in BIG BIG trouble, right?
33,840
Consider our world at 18-19 centuries. Our civilization knows how to print books, build steam machines, we have made first experiments on electricity. And one day the [Mad God Sheogorath](http://elderscrolls.wikia.com/wiki/Sheogorath) is emerged. He can bend the reality by his will. For example, he can violate the principles of conservation of energy - build Perpetuum Mobile just to irritate scientists. He can convert Darwin back into the monkey just to help him prove his theory. He can make forgery of dinosaur skeletons, so we have found caterpillar riding tankosaurus instead of diplodocus. He can resurrect people. And, do a lot of things we are not aware. So, in potential he can spoil every scientific acquired experiments result in a way, that is hard to see. So, the question is: is scientific method still possible in this world? UPD: after 20 years Sheogorath have just vanished. Can we undo his trickery and restore science methods?
2016/01/21
[ "https://worldbuilding.stackexchange.com/questions/33840", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/2763/" ]
**Absolutely** To quote some mouseover text from a certain webcomic: 'We don't use science to prove we're right. We use science to *become* right'. The scientific method is just as valid in your crazy mixed up world as it is now, and will remain so unless the world becomes so crazy that no logical sense can be made of it *at all*. This is because science *isn't* something that we use to show a particular result, it's the way we can explore the world around us. If, suddenly, the rules don't seem to apply because a mad god is messing with us, then the scientific method can still be used to tell us whether or not there is something messing with us. Then it can be used to explore the limits of this entity, and even it's psychology. This then forms a new paradigm of the world, and new theories start to form around that, bolstered by the scientific explorations mankind is making into the nature of our environment *with the mad god in it*. The only way in which this doesn't work is if the mad god is randomly changing everything, all the time, to the point where everything that humanity could possibly know breaks down. At that point it's a somewhat moot point, because the universe will have become a tumultuous maelstrom summoned from the fever dreams of a crazed god. As an example: The mad god has decided to break all experiments that require electrical measurements. Scientists notice that while all their lab equipment is broken, the lights are still on. A simple experiment therefore becomes: when I turn the light switch: do the lights turn on and off? My hypothesis is that the light switch controls the flow of electricity to the light. Now the mad god has a choice. Either the lights continue to work as normal (hooray, the scientific method worked!) or he chooses to change how lightswitches work. If he goes for completely random on-off for lights and light switches, either *the world now works in a different way*, namely, nobody can control the lights, or it's just our scientists that are affected. Either way we then know more about the world around us, either something powerful is messing about with rigorous scientific experiments, or that lights now turn on and off at random, and nothing can stop it. TL:DR: The scientific method is used to figure out how the world works. If the way the world works is that we're captive to the whim of a god who doesn't like science, that's what we'll find out using it. From that point on it's one for the theopsychologists.
This is actually a very common misconception about the scientific method that we seem to teach in schools. The scientific method is not *just* about identifying the "right" laws governing the universe. It is also about building useful models of the universe. In fact, if you are willing to sit down with any real scientist, and use the right philosophical buzz words, you can even get them to admit that they can never provably achieve the former. So let's start to play with some of those philosophical terms! Philosophers call the study of reality "ontology." The word "reality" gets treated many different ways, but intuitively, ontology is looking for what is actually real, not just what appears to be real. Epistemology, on the other hand, is the study of knowledge. Empiricism, a word you may have heard with reference to science, is a branch of epistemology. It studies what we can know through observation of the world around us. The line between these can be seen several ways, but I find the most impressive of them to be the brain-in-a-vat thought experiment. Consider the possibility that you are actually just a brain, sitting in a vat somewhere, being fed neural stimulus like you were part of the Matrix. Ontology would be very interested in the "real world" where you are a brain in a vat, and would call the neural stimulus you are receiving a "simulation." However, just as we saw in the The Matrix, it is remarkably hard to make definitive statements about this reality while you're still jacked into the matrix, and have never observed the outside world. This is the epistomological side: how can one *know* the state of reality? An empirical approach would focus entirely on what can be observed, the stimulus. A 100% empirical scientist would actually not really care whether they are a brain in a vat or not until they identify an observation to defend it (although, in reality, no human is ever 100% anything!) How do we get confused? There are three major categories of thought in logical philosophy. You're almost certainly familiar with deduction and induction. Deduction is going from the general to the specific (all swans are white, so this swan must be white too). Induction is going from the specific to the general (these swans are white, so perhaps all swans are white). There is a third you hear very little about: [abduction](http://plato.stanford.edu/entries/abduction/). Abduction is the ability to infer the best explanation is true. In many discourses, such as science, you end up with many explanations. Maybe your empirical results line up with your theory because your theory is ontologically right, or maybe someone is cleverly massaging the world behind the scenes to fool you. At some point, you may decide the best explanation is that you've found something useful, so you *infer* your theory to be correct. This mode of logic is a fascinating little puzzle because the term "best explanation" leaves so much room for alternatives (read the SEP link above if you're interested). However, any claim of an empirical method, such as science, yielding an ontological truth *must* go through this abductive step. So where does that leave us for the scientific method in the presence of your Mad God Shegorath? Well, from an abductive perspective, the alternative explanations of "Shegorath is just fooling us" starts to become a better explaination, so it becomes harder to use abduction to claim you have arrived at the only worthwhile best possible explanation. You would see additional questioning of scientific results. Enter the Engineer. Engineering and science are tied together intimately, like husband and wife, or perhaps even like conjoined twins. While science provides epistemological ways to "know" things, engineering uses that knowledge to build up the world around us. Of course, science never feeds us perfect knowledge. Only recently did we find out that all of our equations of motions we've been using for a long time get gummed up by relativity. Only recently did we find out that much of the world is non-deterministic thanks to quantum mechanics. Yet what we created from that era is still useful. How? Engineers have a phrase, which I commit to my heart: "All models are wrong, some are useful." We can assume that every model we come up with can be ontologically wrong, because the track record of scientific "knowledge" being revised as new data comes along is 100%. That's not a shortcoming of science, that's actually its strong point: it *always* tries to incorporate the new observations, no matter how undesirable they might be. However, it turns out that for almost everything you or I could want to do, it doesn't have to be perfect. It just has to be close enough to be worth doing. Take teflon, PTFE. Science can develop the molecular structure of PTFE, and say "this is how PTFE works." However, never once will we create a magical perfect PTFE molecule. Every process to make it is slightly flawed. The engineering side is worried about how to use what the science knew about PTFE to coat a non-stick pot. If the science is a *little* wrong, that's okay. We'll do a test run first, to make sure the pots are useful, before selling them! The science is just treated as a guideline -- what really matters is whether the process works or not, not whether it matches exactly the predictions of science. If the science turns out to not be useful for engineering, it will just sit on the shelf until it becomes useful, or dispelled. This is, for example, how we managed to make electronics work for hundreds of years, despite getting the flow of current backwards the entire time. Ben Franklin had to make a guess as to which way the charge was flowing. He guessed wrong, so technically everything we've done with electronics is incorrect. However, his model of electricity was useful enough that there was no need to correct it, until the semiconductor era, where paying attention to what is an electron vs a hole can actually matter. So the scientific method would still be viable in this world with a Mad God. It would simply gravitate towards applications where behaviors are *still* relatively predictable, even after the Mad God. Consider the fact that you're looking at a computer screen right now. If the Mad God were to make the laws of physics too unpredictable, photons would not go in straight lines, and you couldn't read. Of course, it's possible the Mad God decides to only screw with science. He might decide that every science experiment is going to go awry. In this case, he creates all sorts of interesting looping structures as we try to define what a scientific experiment "is." He may actually disappear in a poof of logic, akin to Douglas Adam's god in *Hitchiker's Guide to the Galaxy*! Or he might form a strange loop a. la. Douglas Hofstadter, where he controls the universe, and the universe decides what he will do. If you're going down this path, you're going to have to describe what "viable" means in the question "is the scientific method viable...." If you are presuming an ontological world with such a crazy powerful entity, you are going to have to define your term "viable" in a way which makes sense in their presence. There may also be the question of whether the viability, once defined, can be known by a mere mortal. These questions oft leave philosophers awake at night. As a final fun tidbit, what's to say he hasn't already acted? The ultimate observation, in philosophy, is one done by a being that can think. The ability to do this is called perception. As silly as it may sound, philosophers do not have a clear sense of what perception is, nor how it behaves. Maybe we are just a brain in the jar. Could we perceive it?
8,051,394
Could anybody help me out to get nested tabs through ajax calls. Description: I am having Jquery Tabs with ajax option CODE: ``` $( ".has_ajax_tabs" ).tabs({ ajaxOptions: { error: function( xhr, status, index, anchor ) { $( anchor.hash ).html("<h3>OOPS...Something went wrong!</h3> Couldn't load this tab at this time. Please try again later."); } }, spinner: "Loading...", fxSlide: true }); ``` HTML CODE: ``` <div id="tabs" class="has_ajax_tabs"> <ul> <li><a href="#tabs-1">Profile Details</a></li> <li><a href="nestedTabsLink.php">Users</a></li> </ul> <div id="tabs-1"> Profile Details form here </div> </div> ``` nestedTabsLink.php loaded by Ajax call ``` <div id="tabs-nested" class="has_ajax_tabs"> <ul> <li><a href="#tabs-inner1">Inner Tab1</a></li> <li><a href="#tabs-inner2">Inner Tab2</a></li> </ul> <div id="tabs-inner1"> Nested Tabs1 </div> <div id="tabs-inner2"> Nested Tabs2 </div> </div> ``` ERROR: The loaded nestedTabsLink.php file also having tabs which is not working if loaded by Ajax. Without Ajax it works perfect. Can anybody help me to get the code snippet/guidelines? Thanks
2011/11/08
[ "https://Stackoverflow.com/questions/8051394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
That's a bad idea. The lifetime of a threadpool thread is determined by the code it executes, preferably short and snappy. This is *not* the rule for an STA thread, it must stay active and pump a message loop as long as the COM objects that were created on that thread are not finalized. A requirement that's very incompatible with a TP thread. Trying to do this anyway will just buy you never-ending misery with "COM object that has been separated from its underlying RCW cannot be used" exceptions as well as deadlock. This is why a .NET tp thread is always MTA. You must use a regular Thread.
I have analyzed the source code and found out that SmartThreadPool doesn't support STA threads. The only way to create them is to modify the sources as follows: 1. Add *StartSTAThreads* property to the *STPStartInfo* class. 2. Add ``` if (_stpStartInfo.StartSTAThreads) { workerThread.SetApartmentState(ApartmentState.STA); } ``` to the *SmartThreadPool.StartThreads* method before *workerThread.Start()* call.
8,051,394
Could anybody help me out to get nested tabs through ajax calls. Description: I am having Jquery Tabs with ajax option CODE: ``` $( ".has_ajax_tabs" ).tabs({ ajaxOptions: { error: function( xhr, status, index, anchor ) { $( anchor.hash ).html("<h3>OOPS...Something went wrong!</h3> Couldn't load this tab at this time. Please try again later."); } }, spinner: "Loading...", fxSlide: true }); ``` HTML CODE: ``` <div id="tabs" class="has_ajax_tabs"> <ul> <li><a href="#tabs-1">Profile Details</a></li> <li><a href="nestedTabsLink.php">Users</a></li> </ul> <div id="tabs-1"> Profile Details form here </div> </div> ``` nestedTabsLink.php loaded by Ajax call ``` <div id="tabs-nested" class="has_ajax_tabs"> <ul> <li><a href="#tabs-inner1">Inner Tab1</a></li> <li><a href="#tabs-inner2">Inner Tab2</a></li> </ul> <div id="tabs-inner1"> Nested Tabs1 </div> <div id="tabs-inner2"> Nested Tabs2 </div> </div> ``` ERROR: The loaded nestedTabsLink.php file also having tabs which is not working if loaded by Ajax. Without Ajax it works perfect. Can anybody help me to get the code snippet/guidelines? Thanks
2011/11/08
[ "https://Stackoverflow.com/questions/8051394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
For completeness, the [current version](http://www.codeproject.com/Articles/7933/Smart-Thread-Pool#Feature29) does support STA threads: ``` STPStartInfo stpStartInfo = new STPStartInfo(); stpStartInfo.ApartmentState = ApartmentState.STA; SmartThreadPool stp = new SmartThreadPool(stpStartInfo); ```
I have analyzed the source code and found out that SmartThreadPool doesn't support STA threads. The only way to create them is to modify the sources as follows: 1. Add *StartSTAThreads* property to the *STPStartInfo* class. 2. Add ``` if (_stpStartInfo.StartSTAThreads) { workerThread.SetApartmentState(ApartmentState.STA); } ``` to the *SmartThreadPool.StartThreads* method before *workerThread.Start()* call.
16,660
I'm currently building a functional Lego escalator that is minifigure-scaled and with staircases transitioning from flat platform to stairwell. Here's my progress so far: [![escalator slope design](https://i.stack.imgur.com/OOvDG.png)](https://i.stack.imgur.com/OOvDG.png) But with the design of the staircases hopefully out of the way for now, I've come into an issue with the slope as it is seemingly improbable to build. I tried multiple iterations: technic bricks, technic beams, snot, … but there's only so much I can do on Mecabricks. I don't have the necessary bricks available at my disposal, nor does my local area has any retails which offers the Pick-a-Brick service, therefore I couldn't physically test this build out. Is there any way of building a framework for this slope to hold up at a precise angle of 39.5 degrees? Preferably one that is legal or at least doesn't cause immense stress on the bricks, due to the technical nature of this build? EDIT: Extra images for elaboration: [![Isometric perspective of escalator design](https://i.stack.imgur.com/gmcxy.jpg)](https://i.stack.imgur.com/gmcxy.jpg) [![Design of stair consists of 2 3M shafts, plate 1x2 with holder (vertical), and plate 1x1 with upright holder](https://i.stack.imgur.com/g30r0.jpg)](https://i.stack.imgur.com/g30r0.jpg) I aim to have this escalator to be roughly 4 bricks in width and its height will be dependent on how tall a story might be (probably 9 bricks tall). I don't intend to use the new dedicated escalator piece because I want to design an escalator that is flat at the base and transition into a moving stairwell then back into a flat platform at the top (and vice versa). Basically something of [this](https://www.youtube.com/watch?v=VAjFw7v8QhE) complexity , but at a minifigure scale. EDIT 2: These are the results I yielded when I tried hinge pieces for building a slope: [![Iteration 1](https://i.stack.imgur.com/WSkiJ.png)](https://i.stack.imgur.com/WSkiJ.png) [![Iteration 2](https://i.stack.imgur.com/k4Vvq.png)](https://i.stack.imgur.com/k4Vvq.png) Connector peg with [plate 1x2 with pinhole on bottom](https://www.bricklink.com/v2/catalog/catalogitem.page?P=18677&name=Plate,%20Modified%201%20x%202%20with%20Pin%20Hole%20on%20Bottom&category=%5BPlate,%20Modified%5D#T=C) or any other hinge designs yield the same results. Maybe it could work but since I don't have local access to Bricklink and the likes, I couldn't physically test this out and have only Mecabricks to work with.
2021/10/15
[ "https://bricks.stackexchange.com/questions/16660", "https://bricks.stackexchange.com", "https://bricks.stackexchange.com/users/19067/" ]
Could this work in you case? Using snot brick to build it vertically. [![Slope 45°](https://i.stack.imgur.com/9mNeE.jpg)](https://i.stack.imgur.com/9mNeE.jpg) EDIT 1: The only way I managed to get your angle and snap it correctly is like that. I used stud.io with collision turned on to be sure it could work. I hope this can help you. [![39.5](https://i.stack.imgur.com/Nyvem.png)](https://i.stack.imgur.com/Nyvem.png) [![39.5°](https://i.stack.imgur.com/L6vPG.png)](https://i.stack.imgur.com/L6vPG.png) EDIT 2: I found another solution using bar and bar with clip. This one is much more modulable but maybe less stable. Let me know what you think. [![enter image description here](https://i.stack.imgur.com/K7UNh.png)](https://i.stack.imgur.com/K7UNh.png) EDIT 3: Adapted to use technic beam. [![beam setup](https://i.stack.imgur.com/uJpO7.png)](https://i.stack.imgur.com/uJpO7.png) [![with beam](https://i.stack.imgur.com/2xxMy.png)](https://i.stack.imgur.com/2xxMy.png)
**Update:** Now that I have stud.io installed, I've finally got an upright design for the slope's framework as follows: [![39.5 degrees slope (white) with supporting frameworks (green)](https://i.stack.imgur.com/MTQh3.png)](https://i.stack.imgur.com/MTQh3.png) This design was based off of @Hugo 's suggestion, but modified to use Technic pegs and Technic bricks for better stability.
330,170
I learned British English, but I work exclusively with Americans. I'll often say "Fat lot of good X did for us", and I get confused looks from others. For example, the other day, I said "I think we should have had them take the web development course; fat lot of good the algorithms course did for them" and people have no idea what I mean. A coworker told me that what I'm saying sounds like what someone British would say, and I'm not sure how to Americanize this statement. First: Am I using the term "Fat lot of good" incorrectly? Second: How should I say this in American English?
2022/12/30
[ "https://ell.stackexchange.com/questions/330170", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/151216/" ]
**Just leave out the fat**, in speech, and use a sarcastic tone. "I think we should have had them take the web development course; a lot of good the algorithms course did for them." The fact is that this is an idiomatic expression. And **many Americans** *would in fact understand* "a fat lot of good". Who cares what a coworker says? The expression is not essentially British at all. It's in Merriam Webster like this: a (fat) lot of good idiom informal : no use or help at all "I've brought an umbrella." "A (fat) lot of good that will do now that it's stopped raining!" [Merriam Webster](https://www.merriam-webster.com/dictionary/a%20%28fat%29%20lot%20of%20good)
A whole lot of good would also work. I'm guessing the confusion comes from the fact that "fat" generally refers to being overweight.
3,599,278
I must develop a simple web application to produce reports. I have a single table "contract" and i must return very simple aggregated values : number of documents produced in a time range, average number of pages for documents and so on . The table gets filled by a batch application, users will have roles that will allow them to see only a part of the reports (if they may be called so ). My purpose is : 1. develop a class, which generates the so called reports, opened to future extension (adding new methods to generate new reports for different roles must be easy ) 2. decouple the web graphic interface from the database access I'm evaluating various patterns : decorator, visitor, ... but being the return data so simple i cannot evaluate which apply or even if its the case to use one. Moreover i must do it i less than 5 days. It can be done if i make a so called "smart gui" but as told at point 1, i don't want to get troubles when new roles or method will be added. --- thank you for your answers. I'm sorry, i realize i haven't provided too much infos. I live in a Dilbert world. at the moment i've got the following info : db will be oracle (the concrete db doesn't exist yet) , so no EF, maybe linqtodataset (but i'm new to linq). About new features of the application,due to pravious experiences, the only thing i wish is not to be obliged to propagate changes over the whole application, even if it's simple. that are the reasons i've thougth to design patterns (note i've said "if it's the case" in my question) . I'll KISS it and then will refactor it if needed , as suggested by ladislav mrnka, but i still appreciate any suggestion on how to keep opened to extension the data gathering class
2010/08/30
[ "https://Stackoverflow.com/questions/3599278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
KISS - keep it simple and stupid. You have five days. Create working application and if you have time refactor it to some better solution.
The road to good code is not paved with design patterns. Good code is code that is readable, maintainable, robust, compatible and future-proof. Don’t get me wrong: Design patterns are a great thing because they help categorise, and thus teach, the experience that earlier generations of programmers have accrued. Each design pattern once solved a problem in a way that was not only novel and creative, but also *good*. The corrolary is *not* that a design pattern is necessarily good code when applied to any other problem. Good code requires experience and insight. This includes experience with design patterns, and insight into their applicability and their downsides and pitfalls. That said, my recommendation in your specific case is to learn about the recommended practice regarding web interfaces, database access, etc. Most C# programmers write web applications in ASP.NET; tend to use LINQ-to-Entities or LINQ-to-SQL for database access; and use Windows Forms or WPF for a desktop GUI. Each of these may or may not fulfill the requirements of your particular project. Only you can tell.
3,599,278
I must develop a simple web application to produce reports. I have a single table "contract" and i must return very simple aggregated values : number of documents produced in a time range, average number of pages for documents and so on . The table gets filled by a batch application, users will have roles that will allow them to see only a part of the reports (if they may be called so ). My purpose is : 1. develop a class, which generates the so called reports, opened to future extension (adding new methods to generate new reports for different roles must be easy ) 2. decouple the web graphic interface from the database access I'm evaluating various patterns : decorator, visitor, ... but being the return data so simple i cannot evaluate which apply or even if its the case to use one. Moreover i must do it i less than 5 days. It can be done if i make a so called "smart gui" but as told at point 1, i don't want to get troubles when new roles or method will be added. --- thank you for your answers. I'm sorry, i realize i haven't provided too much infos. I live in a Dilbert world. at the moment i've got the following info : db will be oracle (the concrete db doesn't exist yet) , so no EF, maybe linqtodataset (but i'm new to linq). About new features of the application,due to pravious experiences, the only thing i wish is not to be obliged to propagate changes over the whole application, even if it's simple. that are the reasons i've thougth to design patterns (note i've said "if it's the case" in my question) . I'll KISS it and then will refactor it if needed , as suggested by ladislav mrnka, but i still appreciate any suggestion on how to keep opened to extension the data gathering class
2010/08/30
[ "https://Stackoverflow.com/questions/3599278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
KISS - keep it simple and stupid. You have five days. Create working application and if you have time refactor it to some better solution.
How about you use strategy pattern for the retrieving data? And use interfaces like following to keep it extendable at all times. * IReportFilter: Report filter/criteria set * IReportParams: Gets report parameters * IReportData: Gets the report data in a result set * IReportFormat: Report formatting * IReportRender: Renders the report Just thinking out loud.
14,055,690
can i get the whole `linearlayout` or other layouts converted to bitmap. my code is this : ``` LinearLayout view = (LinearLayout)findViewById(R.id.linear_parent); view.setDrawingCacheEnabled(true); view.buildDrawingCache(); Bitmap bm = view.getDrawingCache(); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.JPEG, 40, bytes); ``` the problem is if layout is larger than the screen size only i get whats on screen & not the whole contents e.g. textview etc. which are currently not on screen but are part of layout. Any suggestions geeks out there. this is way to urgent and important.
2012/12/27
[ "https://Stackoverflow.com/questions/14055690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1882012/" ]
instead of ImageView try *clickable="true"* and *drawableEnd* ``` <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:drawableEnd="@drawable/navigation_icon" android:text="Text" android:clickable="true" /> ```
try to make your xml look like below. ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" > <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="0" android:text="TextView" /> <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:src="@drawable/my_icon" /> </LinearLayout> </LinearLayout> ```
14,055,690
can i get the whole `linearlayout` or other layouts converted to bitmap. my code is this : ``` LinearLayout view = (LinearLayout)findViewById(R.id.linear_parent); view.setDrawingCacheEnabled(true); view.buildDrawingCache(); Bitmap bm = view.getDrawingCache(); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.JPEG, 40, bytes); ``` the problem is if layout is larger than the screen size only i get whats on screen & not the whole contents e.g. textview etc. which are currently not on screen but are part of layout. Any suggestions geeks out there. this is way to urgent and important.
2012/12/27
[ "https://Stackoverflow.com/questions/14055690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1882012/" ]
After lot of googling, I found a good solution of my problem ``` TextView textView =new TextView(this); SpannableStringBuilder ssb = new SpannableStringBuilder( "Here's a smiley how are you " ); Bitmap smiley = BitmapFactory.decodeResource( getResources(), R.drawable.movie_add ); ssb.setSpan( new ImageSpan( smiley ), ssb.length()-1, ssb.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE ); textView.setText( ssb, BufferType.SPANNABLE ); ``` **With the help of above code, you can add image any where in Textview.**
try to make your xml look like below. ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" > <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="0" android:text="TextView" /> <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:src="@drawable/my_icon" /> </LinearLayout> </LinearLayout> ```
14,055,690
can i get the whole `linearlayout` or other layouts converted to bitmap. my code is this : ``` LinearLayout view = (LinearLayout)findViewById(R.id.linear_parent); view.setDrawingCacheEnabled(true); view.buildDrawingCache(); Bitmap bm = view.getDrawingCache(); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.JPEG, 40, bytes); ``` the problem is if layout is larger than the screen size only i get whats on screen & not the whole contents e.g. textview etc. which are currently not on screen but are part of layout. Any suggestions geeks out there. this is way to urgent and important.
2012/12/27
[ "https://Stackoverflow.com/questions/14055690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1882012/" ]
instead of ImageView try *clickable="true"* and *drawableEnd* ``` <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:drawableEnd="@drawable/navigation_icon" android:text="Text" android:clickable="true" /> ```
Use the following layout ``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:gravity="center" android:padding="2dp" android:background="@android:color/transparent" > <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="left" android:padding="1dp" android:layout_gravity="left" android:orientation="horizontal" > <TextView android:id="@+id/contentText1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Medium T" android:gravity="center" android:minLines="2" android:layout_gravity="center" android:textColor="@color/white" android:padding="5dp" android:visibility="invisible" android:textAppearance="?android:attr/textAppearanceMedium" /> <ImageView android:id="@+id/contentImage1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:gravity="center" android:padding="5dp" android:visibility="invisible" android:src="@drawable/browse_product_thumbnail" /> </LinearLayout> </LinearLayout> ``` -Preeya
14,055,690
can i get the whole `linearlayout` or other layouts converted to bitmap. my code is this : ``` LinearLayout view = (LinearLayout)findViewById(R.id.linear_parent); view.setDrawingCacheEnabled(true); view.buildDrawingCache(); Bitmap bm = view.getDrawingCache(); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.JPEG, 40, bytes); ``` the problem is if layout is larger than the screen size only i get whats on screen & not the whole contents e.g. textview etc. which are currently not on screen but are part of layout. Any suggestions geeks out there. this is way to urgent and important.
2012/12/27
[ "https://Stackoverflow.com/questions/14055690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1882012/" ]
After lot of googling, I found a good solution of my problem ``` TextView textView =new TextView(this); SpannableStringBuilder ssb = new SpannableStringBuilder( "Here's a smiley how are you " ); Bitmap smiley = BitmapFactory.decodeResource( getResources(), R.drawable.movie_add ); ssb.setSpan( new ImageSpan( smiley ), ssb.length()-1, ssb.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE ); textView.setText( ssb, BufferType.SPANNABLE ); ``` **With the help of above code, you can add image any where in Textview.**
Use the following layout ``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:gravity="center" android:padding="2dp" android:background="@android:color/transparent" > <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="left" android:padding="1dp" android:layout_gravity="left" android:orientation="horizontal" > <TextView android:id="@+id/contentText1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Medium T" android:gravity="center" android:minLines="2" android:layout_gravity="center" android:textColor="@color/white" android:padding="5dp" android:visibility="invisible" android:textAppearance="?android:attr/textAppearanceMedium" /> <ImageView android:id="@+id/contentImage1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:gravity="center" android:padding="5dp" android:visibility="invisible" android:src="@drawable/browse_product_thumbnail" /> </LinearLayout> </LinearLayout> ``` -Preeya
14,055,690
can i get the whole `linearlayout` or other layouts converted to bitmap. my code is this : ``` LinearLayout view = (LinearLayout)findViewById(R.id.linear_parent); view.setDrawingCacheEnabled(true); view.buildDrawingCache(); Bitmap bm = view.getDrawingCache(); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.JPEG, 40, bytes); ``` the problem is if layout is larger than the screen size only i get whats on screen & not the whole contents e.g. textview etc. which are currently not on screen but are part of layout. Any suggestions geeks out there. this is way to urgent and important.
2012/12/27
[ "https://Stackoverflow.com/questions/14055690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1882012/" ]
After lot of googling, I found a good solution of my problem ``` TextView textView =new TextView(this); SpannableStringBuilder ssb = new SpannableStringBuilder( "Here's a smiley how are you " ); Bitmap smiley = BitmapFactory.decodeResource( getResources(), R.drawable.movie_add ); ssb.setSpan( new ImageSpan( smiley ), ssb.length()-1, ssb.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE ); textView.setText( ssb, BufferType.SPANNABLE ); ``` **With the help of above code, you can add image any where in Textview.**
instead of ImageView try *clickable="true"* and *drawableEnd* ``` <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:drawableEnd="@drawable/navigation_icon" android:text="Text" android:clickable="true" /> ```
8,798,985
I have encountered a problem of socket communication on linux system, the communication process is like below: client send a message to ask the server to do a compute task, and wait for the result message from server after the task completes. But the client would hangs up to wait for the result message if the task costs a long time such as about 40 minutes even though from the server side, the result message has been written to the socket to respond to the client, but it could normally receive the result message if the task costs little time, such as one minute. Additionally, this problem only happens on customer environment, the communication process behaves normally in our testing environment. I have suspected the cause to this problem is the default timeout value of socket is different between customer environment and testing environment, but the follow values are identical on these two environment, and both Client and server. ``` getSoTimeout:0 getReceiveBufferSize:43690 getSendBufferSize:8192 getSoLinger:-1 getTrafficClass:0 getKeepAlive:false getTcpNoDelay:false ``` the codes on CLient are like: ``` Message msg = null; ObjectInputStream in = client.getClient().getInputStream(); //if no message readObject() will hang here while ( true ) { try { Object recObject = in.readObject(); System.out.println("Client received msg."); msg = (Message)recObject; return msg; }catch (Exception e) { e.printStackTrace(); return null; } } ``` the codes on server are like, ``` ObjectOutputStream socketOutStream = getSocketOutputStream(); try { MessageJobComplete msgJobComplete = new MessageJobComplete(reportFile, outputFile ); socketOutStream.writeObject(msgJobComplete); }catch(Exception e) { e.printStackTrace(); } ``` in order to solve this problem, i have added the flush and reset method, but the problem still exists: ``` ObjectOutputStream socketOutStream = getSocketOutputStream(); try { MessageJobComplete msgJobComplete = new MessageJobComplete(reportFile, outputFile ); socketOutStream.flush(); logger.debug("AbstractJob#reply to the socket"); socketOutStream.writeObject(msgJobComplete); socketOutStream.reset(); socketOutStream.flush(); logger.debug("AbstractJob#after Flush Reply"); }catch(Exception e) { e.printStackTrace(); logger.error("Exception when sending MessageJobComplete."+e.getMessage()); } ``` so do anyone knows what the next steps i should do to solve this problem. I guess the cause is the environment setting, but I do not know what the environment factors would affect the socket communication? And the socket using the Tcp/Ip protocal to communicate, the problem is related with the long time task, so what values about tcp would affect the timeout of socket communication? After my analysis about the logs, i found after the message are written to the socket, there were no exceptions are thrown/caught. But always after 15 minutes, there are exceptions in the objectInputStream.readObject() codes snippet of Server Side which is used to accept the request from client. However, socket.getSoTimeout value is 0, so it is very strange that the a Timed out Exception was thrown. ``` {2012-01-09 17:44:13,908} ERROR java.net.SocketException: Connection timed out at java.net.SocketInputStream.socketRead0(Native Method) at java.net.SocketInputStream.read(SocketInputStream.java:146) at sun.security.ssl.InputRecord.readFully(InputRecord.java:312) at sun.security.ssl.InputRecord.read(InputRecord.java:350) at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:809) at sun.security.ssl.SSLSocketImpl.readDataRecord(SSLSocketImpl.java:766) at sun.security.ssl.AppInputStream.read(AppInputStream.java:94) at sun.security.ssl.AppInputStream.read(AppInputStream.java:69) at java.io.ObjectInputStream$PeekInputStream.peek(ObjectInputStream.java:2265) at java.io.ObjectInputStream$BlockDataInputStream.peek(ObjectInputStream.java:2558) at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2568) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1314) at java.io.ObjectInputStream.readObject(ObjectInputStream.java:368) ``` so why the Connection Timed out exceptions are thrown?
2012/01/10
[ "https://Stackoverflow.com/questions/8798985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1124954/" ]
This problem is solved. using the `tcpdump` to capture the messages flows. I have found that while in the application level, `ObjectOutputStream.writeObject()` method was invoked, in the tcp level, many times `[TCP ReTransmission]` were found. So, I concluded that the connection is possibly be dead, although using the `netstat -an` command the tcp connection state still was `ESTABLISHED`. So I wrote a testing application to periodically sent Testing messages as the heart-beating messages from the Server. Then this problem disappeared.
The `read()` methods of `java.io.InputStream` are *blocking* calls., which means they wait "forever" if they are called when there is no data in the stream to read. This is completely expected behaviour and as per the published contract in javadoc if the server does not respond. If you want a non-blocking read, use the `java.nio.*` classes.
70,973,755
iOS 15 Swift 5.5 Trying to understand preferences, but struggling with GeometryReader I crafted this code reading a tutorial, but it doesn't work correctly. The green box should appear over the red dot, the first one. But it is over the centre one. When I tap on the dot, it moves to the third...it feels like SwiftUI drew the whole thing and then changed its mind about the coordinates. Sure I could change the offsets, but that is a hack. Surely SwiftUI should be updating the preferences if the thing moves. ``` import SwiftUI struct ContentView: View { @State private var activeIdx: Int = 0 @State private var rects: [CGRect] = Array<CGRect>(repeating: CGRect(), count: 12) var body: some View { ZStack { RoundedRectangle(cornerRadius: 15).stroke(lineWidth: 3.0).foregroundColor(Color.green) .frame(width: rects[activeIdx].size.width, height: rects[activeIdx].size.height) .offset(x: rects[activeIdx].minX, y: rects[activeIdx].minY) HStack { SubtleView(activeIdx: $activeIdx, idx: 0) SubtleView(activeIdx: $activeIdx, idx: 1) SubtleView(activeIdx: $activeIdx, idx: 2) } .animation(.easeInOut(duration: 1.0), value: rects) }.onPreferenceChange(MyTextPreferenceKey.self) { preferences in for p in preferences { self.rects[p.viewIdx] = p.rect print("p \(p)") } }.coordinateSpace(name: "myZstack") } } struct SubtleView: View { @Binding var activeIdx:Int let idx: Int var body: some View { Circle() .fill(Color.red) .frame(width: 64, height: 64) .background(MyPreferenceViewSetter(idx: idx)) .onTapGesture { activeIdx = idx } } } struct MyTextPreferenceData: Equatable { let viewIdx: Int let rect: CGRect } struct MyTextPreferenceKey: PreferenceKey { typealias Value = [MyTextPreferenceData] static var defaultValue: [MyTextPreferenceData] = [] static func reduce(value: inout [MyTextPreferenceData], nextValue: () -> [MyTextPreferenceData]) { value.append(contentsOf: nextValue()) } } struct MyPreferenceViewSetter: View { let idx: Int var body: some View { GeometryReader { geometry in Rectangle() .fill(Color.clear) .preference(key: MyTextPreferenceKey.self, value: [MyTextPreferenceData(viewIdx: self.idx, rect: geometry.frame(in: .named("myZstack")))]) } } } ``` Tried moving the onPreferences up a level, down a level..attaching it to each view... but still doesn't update...what did I miss here=
2022/02/03
[ "https://Stackoverflow.com/questions/70973755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3069232/" ]
This is an example using `AsyncValue` - It eliminates the `repository` Have your service.dart file like this: ``` final blogServiceProvider = Provider<BlogService>((ref) => BlogService()); class BlogService { Future<AsyncValue<List<BlogPost>>> getBlogPost() async { try { var dio = Dio(); Response response = await dio.get('https://wordpress-site.com/wp-json/wp/v2/posts/'); var posts = (response.data as List); List<BlogPost> list = posts.map<BlogPost>((post) => BlogPost.fromJson(post)).toList(); return AsyncData(list); } catch (e) { return AsyncError("Something went wrong"); } } } ``` And your provider like so: ``` final blogNotifierProvider = StateNotifierProvider<BlogNotifier, AsyncValue<List<BlogPost>>>((ref){ BlogService _service = ref.read(blogServiceProvider); return BlogNotifier(_service); }); class BlogNotifier extends StateNotifier<AsyncValue<List<BlogPost>>> { BlogNotifier(this._service) : super(AsyncLoading()) { getPosts(); } final BlogService _service; void getPosts() async { state = await _service.getBlogPost(); } } ``` Edit: To merge existing posts with new ones, try this: ``` class BlogService { List<BlogPost> _posts = []; Future<AsyncValue<List<BlogPost>>> getBlogPost() async { try { var dio = Dio(); Response response = await dio.get('https://wordpress-site.com/wp-json/wp/v2/posts/'); var posts = (response.data as List); List<BlogPost> list = posts.map<BlogPost>((post) => BlogPost.fromJson(post)).toList(); _posts = list; return AsyncData(list); } catch (e) { return AsyncError("Something went wrong"); } } Future<AsyncValue<List<BlogPost>>> morePosts() async { try { var dio = Dio(); Response response = await dio.get('https://wordpress-site.com/wp-json/wp/v2/posts/?offset=' + length.toString()); var posts = (response.data as List); List<BlogPost> list = posts.map<BlogPost>((post) => BlogPost.fromJson(post)).toList(); _posts.addAll(list); return AsyncData(_posts); } catch (e) { return AsyncError("Something went wrong"); } } } ``` And the notifier class would be: ``` class BlogNotifier extends StateNotifier<AsyncValue<List<BlogPost>>> { BlogNotifier(this._service) : super(AsyncLoading()) { getPosts(); } final BlogService _service; void getPosts() async { state = await _service.getBlogPost(); } void morePosts() async { state = await _service.morePosts(); } } ```
Please best wa create another class to provide data from Api and use drift Package see my screens how i provide data from database (drift is sqlite DB) This is my database class based on sqlite(drift) ``` import 'dart:io'; import 'package:drift/native.dart'; import 'package:mobile_nsk/models/policy/driver.dart'; import 'package:mobile_nsk/models/policy/driver_converter.dart'; import 'package:mobile_nsk/models/policy/holders.dart'; import 'package:mobile_nsk/models/policy/holders_converter.dart'; import 'package:mobile_nsk/models/policy/vehicle.dart'; import 'package:mobile_nsk/models/policy/vehicle_converter.dart'; import 'package:path/path.dart' as p; import 'package:drift/drift.dart'; import 'package:path_provider/path_provider.dart'; part 'database.g.dart'; LazyDatabase _openConnection()=> LazyDatabase(()async{ final dbFolder = await getApplicationDocumentsDirectory(); final file = File(p.join(dbFolder.path, 'db.sqlite')); return NativeDatabase(file,logStatements: true); }); @DriftDatabase(tables: [Holders, Drivers, Vehicles]) class MyDatabase extends _$MyDatabase { MyDatabase() : super(_openConnection()); // Для страхователя Future<List<Holder>> getAllHolders() => select(holders).get(); Stream<List<Holder>> watchAllHolder() => select(holders).watch(); Future insertNewHolder(Holder holder) => into(holders).insert(holder, mode: InsertMode.insertOrReplace); Future deleteHolder(Holder holder) => delete(holders).delete(holder); Future<Holder> getHolderById(Holder holder)=> select(holders).getSingle(); Future insetData(Holder holder) => into(holders).insert(holder, mode: InsertMode.insertOrReplace); Future updateHolder(Holder holder, int id, String phone) async { await update(holders)..where((tbl) => tbl.id.equals(id))..write(HoldersCompanion(phone: Value(phone))); await into(holders).insert(holder, mode: InsertMode.insertOrReplace); } // Для Водителя Future<List<Driver>> getAllDriver() => select(drivers).get(); Stream<List<Driver>> watchAllDriver() => select(drivers).watch(); Future insertNewDriver(Driver driver) => into(drivers).insert(driver, mode: InsertMode.insertOrReplace); Future deleteDriver(Driver driver) => delete(drivers).delete(driver); // Для транспорта Future<List<Vehicle>> getAllVehicles() => select(vehicles).get(); Stream<List<Vehicle>> watchAllVehicle() => select(vehicles).watch(); Future insertNewVehicle(Vehicle vehicle) => into(vehicles).insert(vehicle, mode: InsertMode.insertOrReplace); Future deleteVehicle(Vehicle vehicle) => delete(vehicles).delete(vehicle); // всегда инкрементить версию схему если что то добавил/убрал/изменил/нахуевертил @override int get schemaVersion => 1; } ``` this iss my holder model (ang generate by build\_runner) ``` import 'package:drift/drift.dart'; import 'package:json_annotation/json_annotation.dart' as j; import 'package:mobile_nsk/database/database.dart'; import 'package:mobile_nsk/models/policy/holders_converter.dart'; @UseRowClass(Holder) class Holders extends Table{ IntColumn get id => integer()(); TextColumn get firstName =>text()(); TextColumn get middleName => text()(); TextColumn get lastName => text()(); TextColumn get legalName => text()(); IntColumn get isIndividual => integer()(); TextColumn get iin => text()(); IntColumn get isResident => integer()(); TextColumn get phone => text()(); TextColumn get email => text()(); TextColumn get address => text()(); IntColumn get documentTypeId => integer()(); TextColumn get documentNumber => text()(); TextColumn get documentIssueDate => text()(); TextColumn get classType => text().named("class")(); TextColumn get birthDate => text()(); BoolColumn get isExperienced => boolean()(); BoolColumn get isPrivileged => boolean()(); TextColumn get holders => text().map(const HolderConverter()).nullable()(); @override Set<Column> get primaryKey=> {id}; } @j.JsonSerializable() class Holder implements Insertable<Holder>{ final int id; final String firstName; final String middleName; final String lastName; final String legalName; final int isIndividual; final String iin; final int isResident; final String phone; final String email; final String address; final int documentTypeId; final String documentNumber; final String documentIssueDate; @j.JsonKey(name: "class") final String classType; final String birthDate; final bool isExperienced; final bool isPrivileged; const Holder(this.id, this.firstName, this.middleName, this.lastName, this.legalName, this.isIndividual, this.iin, this.isResident, this.phone, this.email, this.address, this.documentTypeId, this.documentNumber, this.documentIssueDate, this.classType, this.birthDate, this.isExperienced, this.isPrivileged); factory Holder.fromJson(Map<String, dynamic>json)=> Holder( json['id'] as int, json['firstName'] as String? ?? "", json['middleName'] as String? ?? "", json['lastName'] as String? ?? "", json['legalName'] as String? ?? "", json['isIndividual'] as int, json['iin'] as String? ?? "", json['isResident'] as int? ?? 0, json['phone'] as String? ?? "", json['email'] as String? ?? "", json['address'] as String? ?? "", json['documentTypeId'] as int? ?? 0, json['documentNumber'] as String? ?? "", json['documentIssueDate'] as String? ?? "", json['class'] as String? ?? "", json['birthDate'] as String? ?? "", json['isExperienced'] as bool? ?? false, json['isPrivileged'] as bool? ?? false, ); Map<String, dynamic>toJson()=>{ 'id': id, 'firstName':firstName, 'middleName': middleName, 'lastName': lastName, 'legalName': legalName, 'isIndividual': isIndividual, 'iin': iin, 'isResident': isResident, 'phone': phone, 'email': email, 'address': address, 'documentTypeId': documentTypeId, 'documentNumber': documentNumber, 'documentIssueDate': documentIssueDate, 'class': classType, 'birthDate': birthDate, 'isExperienced': isExperienced, 'isPrivileged': isPrivileged, }; @override Map<String, Expression> toColumns(bool nullToAbsent) { return HoldersCompanion( id: Value(id), firstName: Value(firstName), middleName: Value(middleName), lastName: Value(lastName), legalName: Value(legalName), isIndividual: Value(isIndividual), iin: Value(iin), isResident: Value(isResident), phone: Value(phone), email: Value(email), address: Value(address), documentTypeId: Value(documentTypeId), documentNumber: Value(documentNumber), documentIssueDate: Value(documentIssueDate), classType: Value(classType), birthDate: Value(birthDate), isExperienced: Value(isExperienced), isPrivileged: Value(isPrivileged) ).toColumns(nullToAbsent); } } ``` this is my code inser from api to database ``` import 'dart:convert'; import 'dart:developer'; import 'package:http/http.dart' as http; import 'package:mobile_nsk/database/database.dart'; import 'package:mobile_nsk/models/policy/holders.dart'; class HolderProvider { String baseUrl = 'http://172.16.3.49:9096/api/v1'; Future<void> getHolder( String iin,MyDatabase database ) async { final response = await http.get( Uri.parse(baseUrl + '/Customer/get_full_client?iin=$iin'), headers: {'Content-Type': 'application/json'}); if (jsonDecode(response.body)['isExperienced'] != false) { database.insertNewHolder(Holder.fromJson(jsonDecode(response.body))); } else { throw Exception(); } } } ```
2,727,480
Let $(D,\prec) $ be a directed set. Is there a "cofinal chain" in $D $? By chain I mean a $D'\subset D $ such that for all $\lambda,\gamma \in D'$, then $\lambda\prec \gamma $ or $\gamma\prec \lambda $. By cofinal chain I mean a chain $D'$ for which, for every $\gamma\in D $, there is some $\lambda \in D'$ such that $\gamma\prec \lambda $.
2018/04/08
[ "https://math.stackexchange.com/questions/2727480", "https://math.stackexchange.com", "https://math.stackexchange.com/users/177211/" ]
Take $X$ to be your favorite uncountable set. Now take $D$ to be the finite subsets of $X$, ordered by inclusion. Easily, this set is directed. But there are no chains with order type longer than $\omega$, and so no chain can have an uncountable union, and in particular, no chain is cofinal. (If you choose $X$ wisely, then no choice is needed either. And by wisely I just mean not a countable union of finite sets.)
If such chains always existed, say under AC, directed sets would have no use in ZFC since most constructions involving directed sets could be done using such cofinal chains. But it is not the case. For instance let $\omega\_1$ be ordered by divisibility $|$ under Hessenberg product. For $\alpha,\beta\in \omega\_1$, $\alpha,\beta | \alpha \otimes \beta\in \omega\_1$ so this ordered set is directed. The divisibility order is contained in the standard order on $\omega\_1$ so any cofinal chain in $(\omega\_1,|)$ must have cofinality $\omega\_1$. In particular, for such a chain to exist, there must be a countable ordinal $\alpha$ with infinitely many factors (take the $\omega$-th element of the chain). This cannot be as $(\omega\_1,\oplus,\otimes)$ is contained in the UFD formed by taking its Grothendieck ring. There should be simpler and more visual counter examples...
46,774,880
I must be doing something wrong, but the following commented code returns false. Note that WP is returning 'admin' as the 'user\_login', but when that user\_login is used for the `get_user_by()` function it simply returns false. Am I missing something? ``` $user = get_userdata(1); // (admin ID is 1) var_dump($user->user_login); // string(5) 'admin' var_dump(get_user_by('user_login', $user->user_login)); // bool(false) ``` I am running WordPress 4.8.2
2017/10/16
[ "https://Stackoverflow.com/questions/46774880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5433458/" ]
I believe you'll need to use "login" rather by "user\_login" in the get\_user\_by call. See the posssible accepted values of the function here: <https://developer.wordpress.org/reference/functions/get_user_by/>
Try this one it's working ``` $user = get_userdata(1); // admin ID = 1 var_dump($user->user_login); // string(5) 'admin' var_dump(get_user_by('login', $user->user_login)); // return array with data ```
3,098,881
Ive looked and tried but I can't find an answer. In PHP, is it possible to call a class' member function (when that class requires a constructor to receive parameters) without instantiating it as an object? A code example (which gives errors): ``` <?php class Test { private $end=""; function __construct($value) { $this->end=$value; } public function alert($value) { echo $value." ".$this->end; } } //this works: $example=new Test("world"); $example->alert("hello"); //this does not work: echo Test("world")::alert("hello"); ?> ```
2010/06/23
[ "https://Stackoverflow.com/questions/3098881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/373039/" ]
Just do this (in PHP >= 5.4): ``` $t = (new Test("Hello"))->foo("world"); ```
You can't call an instance-level method without an instance. Your syntax: > > > ``` > echo Test("world")::alert("hello"); > > ``` > > doesn't make a lot of sense. Either you're creating an inline instance and discarding it immediately or the `alert()` method has no implicit `this` instance. Assuming: ``` class Test { public function __construct($message) { $this->message = $message; } public function foo($message) { echo "$this->message $message"; } } ``` you can do: ``` $t = new Test("Hello"); $t->foo("world"); ``` but PHP syntax doesn't allow: ``` new Test("Hello")->foo("world"); ``` which would otherwise be the equivalent. There are a few examples of this in PHP (eg using array indexing on a function return). That's just the way it is.
3,098,881
Ive looked and tried but I can't find an answer. In PHP, is it possible to call a class' member function (when that class requires a constructor to receive parameters) without instantiating it as an object? A code example (which gives errors): ``` <?php class Test { private $end=""; function __construct($value) { $this->end=$value; } public function alert($value) { echo $value." ".$this->end; } } //this works: $example=new Test("world"); $example->alert("hello"); //this does not work: echo Test("world")::alert("hello"); ?> ```
2010/06/23
[ "https://Stackoverflow.com/questions/3098881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/373039/" ]
I, too, was looking for a one-liner to accomplish this as part of a single expression for converting dates from one format to another. I like doing this in a single line of code because it is a single logical operation. So, this is a little cryptic, but it lets you instantiate and use a date object within a single line: ``` $newDateString = ($d = new DateTime('2011-08-30') ? $d->format('F d, Y') : ''); ``` Another way to one-line the conversion of date strings from one format to another is to use a helper function to manage the OO parts of the code: ``` function convertDate($oldDateString,$newDateFormatString) { $d = new DateTime($oldDateString); return $d->format($newDateFormatString); } $myNewDate = convertDate($myOldDate,'F d, Y'); ``` I think the object oriented approach is cool and necessary, but it can sometimes be tedious, requiring too many steps to accomplish simple operations.
``` // this does not work: echo Test("world")::alert("hello"); // works, as you are calling not to an object of the class, but to its namespace echo Test::alert("hello"); ```
3,098,881
Ive looked and tried but I can't find an answer. In PHP, is it possible to call a class' member function (when that class requires a constructor to receive parameters) without instantiating it as an object? A code example (which gives errors): ``` <?php class Test { private $end=""; function __construct($value) { $this->end=$value; } public function alert($value) { echo $value." ".$this->end; } } //this works: $example=new Test("world"); $example->alert("hello"); //this does not work: echo Test("world")::alert("hello"); ?> ```
2010/06/23
[ "https://Stackoverflow.com/questions/3098881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/373039/" ]
Unfortunately PHP doesn't have support to do this, but you are a creative and look guy :D You can use an "factory", sample: ``` <?php class Foo { private $__aaa = null; public function __construct($aaa) { $this->__aaa = $aaa; } public static function factory($aaa) { return new Foo($aaa); } public function doX() { return $this->__aaa * 2; } } Foo::factory(10)->doX(); // outputs 20 ```
Just do this (in PHP >= 5.4): ``` $t = (new Test("Hello"))->foo("world"); ```
3,098,881
Ive looked and tried but I can't find an answer. In PHP, is it possible to call a class' member function (when that class requires a constructor to receive parameters) without instantiating it as an object? A code example (which gives errors): ``` <?php class Test { private $end=""; function __construct($value) { $this->end=$value; } public function alert($value) { echo $value." ".$this->end; } } //this works: $example=new Test("world"); $example->alert("hello"); //this does not work: echo Test("world")::alert("hello"); ?> ```
2010/06/23
[ "https://Stackoverflow.com/questions/3098881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/373039/" ]
For this you can do a <https://www.php.net/manual/en/reflectionclass.newinstancewithoutconstructor.php> reflect your class and trigger the new instance without constructor. Here a sample code: ``` <?php class Test { private $end=""; function __construct($value) { $this->end=$value; } public function alert($value) { echo $value." ".$this->end; } public function end($value) { $this->end = $value; return $this; // return Test object so that you can chain to other function method. } } // Solution #1: // reflect your class. $reflector = new \ReflectionClass('Test'); // Then create a new instance without Constructor. // This will ignore the constructor BUT it will create a new instance of class Test. $say = $reflector->newInstanceWithoutConstructor(); // use end method that will return the Test object, then you can chain the alert() $say->end('World!')->alert("Hello"); // output: Hello World! ?> ```
``` // this does not work: echo Test("world")::alert("hello"); // works, as you are calling not to an object of the class, but to its namespace echo Test::alert("hello"); ```
3,098,881
Ive looked and tried but I can't find an answer. In PHP, is it possible to call a class' member function (when that class requires a constructor to receive parameters) without instantiating it as an object? A code example (which gives errors): ``` <?php class Test { private $end=""; function __construct($value) { $this->end=$value; } public function alert($value) { echo $value." ".$this->end; } } //this works: $example=new Test("world"); $example->alert("hello"); //this does not work: echo Test("world")::alert("hello"); ?> ```
2010/06/23
[ "https://Stackoverflow.com/questions/3098881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/373039/" ]
Unfortunately PHP doesn't have support to do this, but you are a creative and look guy :D You can use an "factory", sample: ``` <?php class Foo { private $__aaa = null; public function __construct($aaa) { $this->__aaa = $aaa; } public static function factory($aaa) { return new Foo($aaa); } public function doX() { return $this->__aaa * 2; } } Foo::factory(10)->doX(); // outputs 20 ```
I, too, was looking for a one-liner to accomplish this as part of a single expression for converting dates from one format to another. I like doing this in a single line of code because it is a single logical operation. So, this is a little cryptic, but it lets you instantiate and use a date object within a single line: ``` $newDateString = ($d = new DateTime('2011-08-30') ? $d->format('F d, Y') : ''); ``` Another way to one-line the conversion of date strings from one format to another is to use a helper function to manage the OO parts of the code: ``` function convertDate($oldDateString,$newDateFormatString) { $d = new DateTime($oldDateString); return $d->format($newDateFormatString); } $myNewDate = convertDate($myOldDate,'F d, Y'); ``` I think the object oriented approach is cool and necessary, but it can sometimes be tedious, requiring too many steps to accomplish simple operations.
3,098,881
Ive looked and tried but I can't find an answer. In PHP, is it possible to call a class' member function (when that class requires a constructor to receive parameters) without instantiating it as an object? A code example (which gives errors): ``` <?php class Test { private $end=""; function __construct($value) { $this->end=$value; } public function alert($value) { echo $value." ".$this->end; } } //this works: $example=new Test("world"); $example->alert("hello"); //this does not work: echo Test("world")::alert("hello"); ?> ```
2010/06/23
[ "https://Stackoverflow.com/questions/3098881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/373039/" ]
You can't call an instance-level method without an instance. Your syntax: > > > ``` > echo Test("world")::alert("hello"); > > ``` > > doesn't make a lot of sense. Either you're creating an inline instance and discarding it immediately or the `alert()` method has no implicit `this` instance. Assuming: ``` class Test { public function __construct($message) { $this->message = $message; } public function foo($message) { echo "$this->message $message"; } } ``` you can do: ``` $t = new Test("Hello"); $t->foo("world"); ``` but PHP syntax doesn't allow: ``` new Test("Hello")->foo("world"); ``` which would otherwise be the equivalent. There are a few examples of this in PHP (eg using array indexing on a function return). That's just the way it is.
``` // this does not work: echo Test("world")::alert("hello"); // works, as you are calling not to an object of the class, but to its namespace echo Test::alert("hello"); ```
3,098,881
Ive looked and tried but I can't find an answer. In PHP, is it possible to call a class' member function (when that class requires a constructor to receive parameters) without instantiating it as an object? A code example (which gives errors): ``` <?php class Test { private $end=""; function __construct($value) { $this->end=$value; } public function alert($value) { echo $value." ".$this->end; } } //this works: $example=new Test("world"); $example->alert("hello"); //this does not work: echo Test("world")::alert("hello"); ?> ```
2010/06/23
[ "https://Stackoverflow.com/questions/3098881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/373039/" ]
Unfortunately PHP doesn't have support to do this, but you are a creative and look guy :D You can use an "factory", sample: ``` <?php class Foo { private $__aaa = null; public function __construct($aaa) { $this->__aaa = $aaa; } public static function factory($aaa) { return new Foo($aaa); } public function doX() { return $this->__aaa * 2; } } Foo::factory(10)->doX(); // outputs 20 ```
You can't call an instance-level method without an instance. Your syntax: > > > ``` > echo Test("world")::alert("hello"); > > ``` > > doesn't make a lot of sense. Either you're creating an inline instance and discarding it immediately or the `alert()` method has no implicit `this` instance. Assuming: ``` class Test { public function __construct($message) { $this->message = $message; } public function foo($message) { echo "$this->message $message"; } } ``` you can do: ``` $t = new Test("Hello"); $t->foo("world"); ``` but PHP syntax doesn't allow: ``` new Test("Hello")->foo("world"); ``` which would otherwise be the equivalent. There are a few examples of this in PHP (eg using array indexing on a function return). That's just the way it is.
3,098,881
Ive looked and tried but I can't find an answer. In PHP, is it possible to call a class' member function (when that class requires a constructor to receive parameters) without instantiating it as an object? A code example (which gives errors): ``` <?php class Test { private $end=""; function __construct($value) { $this->end=$value; } public function alert($value) { echo $value." ".$this->end; } } //this works: $example=new Test("world"); $example->alert("hello"); //this does not work: echo Test("world")::alert("hello"); ?> ```
2010/06/23
[ "https://Stackoverflow.com/questions/3098881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/373039/" ]
Unfortunately PHP doesn't have support to do this, but you are a creative and look guy :D You can use an "factory", sample: ``` <?php class Foo { private $__aaa = null; public function __construct($aaa) { $this->__aaa = $aaa; } public static function factory($aaa) { return new Foo($aaa); } public function doX() { return $this->__aaa * 2; } } Foo::factory(10)->doX(); // outputs 20 ```
``` // this does not work: echo Test("world")::alert("hello"); // works, as you are calling not to an object of the class, but to its namespace echo Test::alert("hello"); ```
3,098,881
Ive looked and tried but I can't find an answer. In PHP, is it possible to call a class' member function (when that class requires a constructor to receive parameters) without instantiating it as an object? A code example (which gives errors): ``` <?php class Test { private $end=""; function __construct($value) { $this->end=$value; } public function alert($value) { echo $value." ".$this->end; } } //this works: $example=new Test("world"); $example->alert("hello"); //this does not work: echo Test("world")::alert("hello"); ?> ```
2010/06/23
[ "https://Stackoverflow.com/questions/3098881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/373039/" ]
I, too, was looking for a one-liner to accomplish this as part of a single expression for converting dates from one format to another. I like doing this in a single line of code because it is a single logical operation. So, this is a little cryptic, but it lets you instantiate and use a date object within a single line: ``` $newDateString = ($d = new DateTime('2011-08-30') ? $d->format('F d, Y') : ''); ``` Another way to one-line the conversion of date strings from one format to another is to use a helper function to manage the OO parts of the code: ``` function convertDate($oldDateString,$newDateFormatString) { $d = new DateTime($oldDateString); return $d->format($newDateFormatString); } $myNewDate = convertDate($myOldDate,'F d, Y'); ``` I think the object oriented approach is cool and necessary, but it can sometimes be tedious, requiring too many steps to accomplish simple operations.
For this you can do a <https://www.php.net/manual/en/reflectionclass.newinstancewithoutconstructor.php> reflect your class and trigger the new instance without constructor. Here a sample code: ``` <?php class Test { private $end=""; function __construct($value) { $this->end=$value; } public function alert($value) { echo $value." ".$this->end; } public function end($value) { $this->end = $value; return $this; // return Test object so that you can chain to other function method. } } // Solution #1: // reflect your class. $reflector = new \ReflectionClass('Test'); // Then create a new instance without Constructor. // This will ignore the constructor BUT it will create a new instance of class Test. $say = $reflector->newInstanceWithoutConstructor(); // use end method that will return the Test object, then you can chain the alert() $say->end('World!')->alert("Hello"); // output: Hello World! ?> ```
3,098,881
Ive looked and tried but I can't find an answer. In PHP, is it possible to call a class' member function (when that class requires a constructor to receive parameters) without instantiating it as an object? A code example (which gives errors): ``` <?php class Test { private $end=""; function __construct($value) { $this->end=$value; } public function alert($value) { echo $value." ".$this->end; } } //this works: $example=new Test("world"); $example->alert("hello"); //this does not work: echo Test("world")::alert("hello"); ?> ```
2010/06/23
[ "https://Stackoverflow.com/questions/3098881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/373039/" ]
Unfortunately PHP doesn't have support to do this, but you are a creative and look guy :D You can use an "factory", sample: ``` <?php class Foo { private $__aaa = null; public function __construct($aaa) { $this->__aaa = $aaa; } public static function factory($aaa) { return new Foo($aaa); } public function doX() { return $this->__aaa * 2; } } Foo::factory(10)->doX(); // outputs 20 ```
For this you can do a <https://www.php.net/manual/en/reflectionclass.newinstancewithoutconstructor.php> reflect your class and trigger the new instance without constructor. Here a sample code: ``` <?php class Test { private $end=""; function __construct($value) { $this->end=$value; } public function alert($value) { echo $value." ".$this->end; } public function end($value) { $this->end = $value; return $this; // return Test object so that you can chain to other function method. } } // Solution #1: // reflect your class. $reflector = new \ReflectionClass('Test'); // Then create a new instance without Constructor. // This will ignore the constructor BUT it will create a new instance of class Test. $say = $reflector->newInstanceWithoutConstructor(); // use end method that will return the Test object, then you can chain the alert() $say->end('World!')->alert("Hello"); // output: Hello World! ?> ```
49,148,842
I am working on a show page based on the `match.params` from react router 4. For some reason, some functions runs 3 times which gives me the first 2 times undefined and the third time the result I want. So I have this Show component which have the props "projects" from the main component. In this show component I do a find function on the array with the props projects inside of it. This must return a 1 item with the `project.id` equel to `match.params.id`. This is going good, and If I visit the page by clicking on a button (through the application) I get the page with the right project and properties (e.g. `project.name`). But If I do a reload or visit the page by using an url in the browser, I get an error saying property name is undefined. If I look in the console I see that my console.logs are fired 3 times. Like I said, the first 2 are undefined and the third is giving me the result I want. I guess the first 2 are resulting in the error I get. My Show component ``` import React from 'react' import { Button } from 'reactstrap' const Show = ({match, projects}) => { let project = projects.find((project) => { //Return project with the id equel to the match.params.id return project.id == match.params.id; }); //Both these console.logs runs 3 times when visiting a link by url console.log(project); //this one gives me 2 times undefined, third time is the right item console.log(match.params.id) return( <div className="container p-40"> <div className="projects-header"> {/* If I echo project.name it will gives me 'cannot read property 'name' of undefined' */} <h2>Project '{match.params.id}' {/* {project.name} */}</h2> <Button className="btn btn-primary" onClick={() => console.log('save')}>Save</Button> </div> <div className="project-edit"> </div> </div> ); }; export default Show; ``` The route in the parent component ``` <Route exact path="/projects/show/:id" render={(props) => <Show {...props} projects={this.state.projects} />} /> ``` Someone with a good solution for this problem? I find it a problem that my users can't route by the url. I don't know why my show component fires 3 times either by url/reload. Edit (Added parent component): ``` //Import react import React, { Component } from 'react'; //Import custom components import Sidebar from './components/js/Sidebar' import Dashboard from './components/js/Dashboard' import Projects from './components/js/Projects' import Show from './components/js/projects/Show' //Import styles import './App.css'; //3rd party deps import { BrowserRouter as Router, Route } from "react-router-dom"; import axios from 'axios' class App extends Component { constructor() { super(); this.state = { //Times / Time tracking times: [], timer: false, currentTimer: 0, //Current task currentTask: { id: 3, title: '', project_id: { id: '', name: '', color: '' }, date: '', time_total: '' }, //Projects projects: [] } this.addTask = this.addTask.bind(this); this.startTimer = this.startTimer.bind(this); this.stopTimer = this.stopTimer.bind(this); this.addProject = this.addProject.bind(this); } addTask = (task) => { let newArray = this.state.times.slice(); newArray.push(task); this.setState({times: newArray, currentTimer: 0, timer: false}); clearInterval(this.timerID); } addProject = (project) => { let newArray = this.state.projects.slice(); newArray.push(project); this.setState({ projects: newArray }); } startTimer() { let sec = this.state.currentTimer; const start = Date.now(); this.setState({ timer: true }); this.timerID = setInterval(() => { let time = new Date() - (start - sec * 1000); this.setState({ currentTimer: Math.round(time / 1000)}); }, 1000); } stopTimer() { this.setState({ timer: false }); console.log('stopped'); clearInterval(this.timerID); //Clear interval here } componentDidMount() { // Make a request for a user with a given ID axios.get('/Sample.json') .then((response) => { this.setState({times: response.data}); }); axios.get('/Projects.json') .then((response) => { this.setState({projects: response.data}); }); } render() { return ( <Router> <div className="page-wrapper"> <Sidebar /> <Route exact path="/" render={() => <Dashboard times={this.state.times} timer={this.state.timer} startTimer={this.startTimer} stopTimer={this.stopTimer} currentTimer={this.state.currentTimer} addTask={this.addTask} />} /> <Route exact path="/projects" render={() => <Projects projects={this.state.projects} addProject={this.addProject} />} /> <Route exact path="/projects/show/:id" render={(props) => <Show {...props} projects={this.state.projects} />} /> </div> </Router> ); } } export default App; ```
2018/03/07
[ "https://Stackoverflow.com/questions/49148842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5503094/" ]
Without altering the order of your data, we can do the following: ``` import pandas as pd from io import StringIO data = StringIO('''id,user,timestamp,song 0,user_000001,05-05-09 12:08,The Start of Something 1,user_000001,04-05-09 14:54,My Sharona 2,user_000001,04-05-09 14:52,Caught by the river 3,user_000001,04-05-09 14:42,Swim 19,user_000001,03-05-09 15:56,Cover me 20,user_000001,03-05-09 15:50,Oh Holy Night 1048550,user_000050, 25-01-07 8:51,I Hung My Head 1048551,user_000050, 25-01-07 8:48,Slider 1048552,user_000050,24-01-07 22:57,Joy 1048553,user_000050,24-01-07 22:53,Crazy Eights 1048554,user_000050,24-01-07 22:48,Steady State 1048555,user_000050,24-01-07 22:42,Maple Leaves (7" Version)''') def time_elapsed(grp, session_length): grp['MinsElapsed'] = (grp['timestamp'] - grp['timestamp'].shift(-1)) / pd.Timedelta(minutes=1) grp['Session'] = (grp['MinsElapsed'] > session_length)[::-1].astype(int).cumsum()[::-1] return grp df = pd.read_csv(data) df['timestamp'] = pd.to_datetime(df['timestamp']) df = df.groupby('user').apply(time_elapsed, session_length=20) print(df) ``` We group by user, and work out the time difference between the row below (`.shift(-1)`) in minutes. We then check if this column returns a value larger than the session length, convert that to an integer and apply a cumulative sum. As the times are in descending order, to get this to work properly we have to reverse the entire column before doing the cumulative sum, and then reset it afterwards. This gives us: ``` id user timestamp song MinsElapsed Session 0 0 user_000001 2009-05-05 12:08:00 The Start of Something 43034.0 2 1 1 user_000001 2009-04-05 14:54:00 My Sharona 2.0 1 2 2 user_000001 2009-04-05 14:52:00 Caught by the river 10.0 1 3 3 user_000001 2009-04-05 14:42:00 Swim 44566.0 1 4 19 user_000001 2009-03-05 15:56:00 Cover me 6.0 0 5 20 user_000001 2009-03-05 15:50:00 Oh Holy Night NaN 0 6 1048550 user_000050 2007-01-25 08:51:00 I Hung My Head 3.0 1 7 1048551 user_000050 2007-01-25 08:48:00 Slider 591.0 1 8 1048552 user_000050 2007-01-24 22:57:00 Joy 4.0 0 9 1048553 user_000050 2007-01-24 22:53:00 Crazy Eights 5.0 0 10 1048554 user_000050 2007-01-24 22:48:00 Steady State 6.0 0 11 1048555 user_000050 2007-01-24 22:42:00 Maple Leaves (7" Version) NaN 0 ``` **EDIT:** To get the first and last times on songs in the session and the length of the session, we can do the following: ``` session_length = df.groupby(['user', 'Session'])['timestamp'] \ .agg(['min', 'max']) \ .reset_index() session_length['Length (mins)'] = (session_length['max'] -session_length['min']) / pd.Timedelta(minutes=1) ``` Which gives us: ``` user Session min max Length (mins) 0 user_000001 0 2009-03-05 15:50:00 2009-03-05 15:56:00 6.0 1 user_000001 1 2009-04-05 14:42:00 2009-04-05 14:54:00 12.0 2 user_000001 2 2009-05-05 12:08:00 2009-05-05 12:08:00 0.0 3 user_000050 0 2007-01-24 22:42:00 2007-01-24 22:57:00 15.0 4 user_000050 1 2007-01-25 08:48:00 2007-01-25 08:51:00 3.0 ```
This works, but I've reordered the data per user and timestamp ascending: ``` df['timestamp'] = pd.to_datetime(df['timestamp'], format='%d-%m-%y %H:%M') df=df.sort_values(['user', 'timestamp']) session = 1000 def counter(clause): global session if not clause: session += 1 return session df[['u', 't']] = df[['user', 'timestamp']].shift(-1).ffill() df['session_id'] = df.apply(lambda x: counter(all([[x['user']==x['u']], (x['timestamp']-x['t']) >= -pd.Timedelta(minutes=20)])), axis=1) ```
30,669,015
I have a tkinter 'Text' and 'Scrollbar' working fine. In my program in the text window automatically lines will keep on adding. So When a new line of text is inserted and data reached out of limit I would like the text and scrollbar to be scrolled to the bottom automatically, so that the latest line of text is always shown. How to do this? Also how to link the scroll of text window and scroll bar, because when I do scrolling over the text window scroll wont happen. Only way I observed is to drag the scroll bar. ``` scrollbar = Tkinter.Scrollbar(group4.interior()) scrollbar.pack(side = 'right',fill='y') Details1 = Output() outputwindow = Tkinter.Text(group4.interior(), yscrollcommand = scrollbar.set,wrap = "word",width = 200,font = "{Times new Roman} 9") outputwindow.pack( side = 'left',fill='y') scrollbar.config( command = outputwindow.yview ) outputwindow.yview('end') outputwindow.config(yscrollcommand=scrollbar.set) outputwindow.insert('end',Details1) ``` In the program the function output() will continuously send data, which should scroll Thanks in advance,
2015/06/05
[ "https://Stackoverflow.com/questions/30669015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4946244/" ]
You can cause the text widget to scroll to any location with the `see` which takes an index. For example, to make the last line of the widget visible you can use the index `"end"`: ``` outputwindow.see("end") ``` Here's a complete working example: ``` import time try: # python 2.x import Tkinter as tk except ImportError: # python 3.x import tkinter as tk class Example(tk.Frame): def __init__(self, *args, **kwargs): tk.Frame.__init__(self, *args, **kwargs) self.text = tk.Text(self, height=6, width=40) self.vsb = tk.Scrollbar(self, orient="vertical", command=self.text.yview) self.text.configure(yscrollcommand=self.vsb.set) self.vsb.pack(side="right", fill="y") self.text.pack(side="left", fill="both", expand=True) self.add_timestamp() def add_timestamp(self): self.text.insert("end", time.ctime() + "\n") self.text.see("end") self.after(1000, self.add_timestamp) if __name__ == "__main__": root =tk.Tk() frame = Example(root) frame.pack(fill="both", expand=True) root.mainloop() ```
Take a look at `Text.see(...)` method. ``` TextWidget.insert(tk.END, str(new_txt)) TextWidget.see(tk.END) ``` I used this pattern to add (aka `insert`) text `new_txt` to my output window and scroll (`see`) to the bottom (`tk.END`)
30,669,015
I have a tkinter 'Text' and 'Scrollbar' working fine. In my program in the text window automatically lines will keep on adding. So When a new line of text is inserted and data reached out of limit I would like the text and scrollbar to be scrolled to the bottom automatically, so that the latest line of text is always shown. How to do this? Also how to link the scroll of text window and scroll bar, because when I do scrolling over the text window scroll wont happen. Only way I observed is to drag the scroll bar. ``` scrollbar = Tkinter.Scrollbar(group4.interior()) scrollbar.pack(side = 'right',fill='y') Details1 = Output() outputwindow = Tkinter.Text(group4.interior(), yscrollcommand = scrollbar.set,wrap = "word",width = 200,font = "{Times new Roman} 9") outputwindow.pack( side = 'left',fill='y') scrollbar.config( command = outputwindow.yview ) outputwindow.yview('end') outputwindow.config(yscrollcommand=scrollbar.set) outputwindow.insert('end',Details1) ``` In the program the function output() will continuously send data, which should scroll Thanks in advance,
2015/06/05
[ "https://Stackoverflow.com/questions/30669015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4946244/" ]
You can cause the text widget to scroll to any location with the `see` which takes an index. For example, to make the last line of the widget visible you can use the index `"end"`: ``` outputwindow.see("end") ``` Here's a complete working example: ``` import time try: # python 2.x import Tkinter as tk except ImportError: # python 3.x import tkinter as tk class Example(tk.Frame): def __init__(self, *args, **kwargs): tk.Frame.__init__(self, *args, **kwargs) self.text = tk.Text(self, height=6, width=40) self.vsb = tk.Scrollbar(self, orient="vertical", command=self.text.yview) self.text.configure(yscrollcommand=self.vsb.set) self.vsb.pack(side="right", fill="y") self.text.pack(side="left", fill="both", expand=True) self.add_timestamp() def add_timestamp(self): self.text.insert("end", time.ctime() + "\n") self.text.see("end") self.after(1000, self.add_timestamp) if __name__ == "__main__": root =tk.Tk() frame = Example(root) frame.pack(fill="both", expand=True) root.mainloop() ```
although very useful, using Text.see(...) in the above manner defeats the purpose of having a scrollbar. Better would be insert text at "0." instead of tk.END. That way, it initially autoscrolls, but you can drag it down to anywhere and it will stay there (while updating its range as more text is added, but the text you see remains constant until you scroll elsewhere). Once you want it to autoscroll again, you simply slide the scrollbar all the way back to the top. Another solution (which wouldn't affect the flow direction of incoming text) would be to add some extra logic, such as a checkbox, then everytime you update Text, check that checkbox's state before you decide whether or not to call Text.see(...). I don't know if there is a more elegant solution.
30,669,015
I have a tkinter 'Text' and 'Scrollbar' working fine. In my program in the text window automatically lines will keep on adding. So When a new line of text is inserted and data reached out of limit I would like the text and scrollbar to be scrolled to the bottom automatically, so that the latest line of text is always shown. How to do this? Also how to link the scroll of text window and scroll bar, because when I do scrolling over the text window scroll wont happen. Only way I observed is to drag the scroll bar. ``` scrollbar = Tkinter.Scrollbar(group4.interior()) scrollbar.pack(side = 'right',fill='y') Details1 = Output() outputwindow = Tkinter.Text(group4.interior(), yscrollcommand = scrollbar.set,wrap = "word",width = 200,font = "{Times new Roman} 9") outputwindow.pack( side = 'left',fill='y') scrollbar.config( command = outputwindow.yview ) outputwindow.yview('end') outputwindow.config(yscrollcommand=scrollbar.set) outputwindow.insert('end',Details1) ``` In the program the function output() will continuously send data, which should scroll Thanks in advance,
2015/06/05
[ "https://Stackoverflow.com/questions/30669015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4946244/" ]
You can cause the text widget to scroll to any location with the `see` which takes an index. For example, to make the last line of the widget visible you can use the index `"end"`: ``` outputwindow.see("end") ``` Here's a complete working example: ``` import time try: # python 2.x import Tkinter as tk except ImportError: # python 3.x import tkinter as tk class Example(tk.Frame): def __init__(self, *args, **kwargs): tk.Frame.__init__(self, *args, **kwargs) self.text = tk.Text(self, height=6, width=40) self.vsb = tk.Scrollbar(self, orient="vertical", command=self.text.yview) self.text.configure(yscrollcommand=self.vsb.set) self.vsb.pack(side="right", fill="y") self.text.pack(side="left", fill="both", expand=True) self.add_timestamp() def add_timestamp(self): self.text.insert("end", time.ctime() + "\n") self.text.see("end") self.after(1000, self.add_timestamp) if __name__ == "__main__": root =tk.Tk() frame = Example(root) frame.pack(fill="both", expand=True) root.mainloop() ```
Add this after the insert TextBox.yview(END)
30,669,015
I have a tkinter 'Text' and 'Scrollbar' working fine. In my program in the text window automatically lines will keep on adding. So When a new line of text is inserted and data reached out of limit I would like the text and scrollbar to be scrolled to the bottom automatically, so that the latest line of text is always shown. How to do this? Also how to link the scroll of text window and scroll bar, because when I do scrolling over the text window scroll wont happen. Only way I observed is to drag the scroll bar. ``` scrollbar = Tkinter.Scrollbar(group4.interior()) scrollbar.pack(side = 'right',fill='y') Details1 = Output() outputwindow = Tkinter.Text(group4.interior(), yscrollcommand = scrollbar.set,wrap = "word",width = 200,font = "{Times new Roman} 9") outputwindow.pack( side = 'left',fill='y') scrollbar.config( command = outputwindow.yview ) outputwindow.yview('end') outputwindow.config(yscrollcommand=scrollbar.set) outputwindow.insert('end',Details1) ``` In the program the function output() will continuously send data, which should scroll Thanks in advance,
2015/06/05
[ "https://Stackoverflow.com/questions/30669015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4946244/" ]
Take a look at `Text.see(...)` method. ``` TextWidget.insert(tk.END, str(new_txt)) TextWidget.see(tk.END) ``` I used this pattern to add (aka `insert`) text `new_txt` to my output window and scroll (`see`) to the bottom (`tk.END`)
although very useful, using Text.see(...) in the above manner defeats the purpose of having a scrollbar. Better would be insert text at "0." instead of tk.END. That way, it initially autoscrolls, but you can drag it down to anywhere and it will stay there (while updating its range as more text is added, but the text you see remains constant until you scroll elsewhere). Once you want it to autoscroll again, you simply slide the scrollbar all the way back to the top. Another solution (which wouldn't affect the flow direction of incoming text) would be to add some extra logic, such as a checkbox, then everytime you update Text, check that checkbox's state before you decide whether or not to call Text.see(...). I don't know if there is a more elegant solution.
30,669,015
I have a tkinter 'Text' and 'Scrollbar' working fine. In my program in the text window automatically lines will keep on adding. So When a new line of text is inserted and data reached out of limit I would like the text and scrollbar to be scrolled to the bottom automatically, so that the latest line of text is always shown. How to do this? Also how to link the scroll of text window and scroll bar, because when I do scrolling over the text window scroll wont happen. Only way I observed is to drag the scroll bar. ``` scrollbar = Tkinter.Scrollbar(group4.interior()) scrollbar.pack(side = 'right',fill='y') Details1 = Output() outputwindow = Tkinter.Text(group4.interior(), yscrollcommand = scrollbar.set,wrap = "word",width = 200,font = "{Times new Roman} 9") outputwindow.pack( side = 'left',fill='y') scrollbar.config( command = outputwindow.yview ) outputwindow.yview('end') outputwindow.config(yscrollcommand=scrollbar.set) outputwindow.insert('end',Details1) ``` In the program the function output() will continuously send data, which should scroll Thanks in advance,
2015/06/05
[ "https://Stackoverflow.com/questions/30669015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4946244/" ]
Take a look at `Text.see(...)` method. ``` TextWidget.insert(tk.END, str(new_txt)) TextWidget.see(tk.END) ``` I used this pattern to add (aka `insert`) text `new_txt` to my output window and scroll (`see`) to the bottom (`tk.END`)
Add this after the insert TextBox.yview(END)
30,591,025
I have a problem similar to this one: [SFINAE tried with bool gives compiler error: "template argument ‘T::value’ involves template parameter"](https://stackoverflow.com/questions/7776448/sfinae-tried-with-bool-gives-compiler-error-template-argument-tvalue-invol) I want to define a trait that tells if a complex representation is an array of structs, where real values are never AoS hence no user defined specilization should be required, but for complex you'd always need one: ``` /** * Evaluates to a true type if the given complex type is an Array of Structs, false otherwise * Defaults to false for Real values */ template< typename T, bool T_isComplex = IsComplex<T>::value > struct IsAoS: std::false_type{}; /** * Undefined for (unknown) complex types */ template< typename T > struct IsAoS< T, true >; ``` Specializations are done in the std-way by deriving from std::true/false\_type. The problem is: With this implementation I get the "template argument involves template parameter(s)" error (which is explained in the linked question) but if i switch to types (ommit "::value" in first template and change true to true\_type in 2nd) Complex types won't match the 2nd template anymore because the only derive from std::true\_type and ARE NOT std::true\_type. Only solution I can think of is using expression SFINAE and change the 2nd parameter of the main template to default void and an enable\_if for the real case (isComplex==false). Anything better?
2015/06/02
[ "https://Stackoverflow.com/questions/30591025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1930508/" ]
On the assumption that `IsAoS<T>`'s desired behavior is: * If `IsComplex<T>::value` is `false`, it defaults to `false_type`; * Otherwise, it is an error unless the user provides a specialization. It's straightforward to implement with a `static_assert`; no default template argument needed: ``` template< typename T > struct IsAoS: std::false_type { static_assert(!IsComplex<T>::value, "A user specialization must be provided for Complex types"); }; ``` --- If you want the default argument trickery, just use a wrapper layer: ``` namespace detail { template< typename T, bool T_isComplex = IsComplex<T>::value > struct IsAoS_impl: std::false_type{}; /** * Undefined for (unknown) complex types */ template< typename T > struct IsAoS_impl< T, true >; } template<class T> struct IsAoS : detail::IsAoS_impl<T> {}; ``` Users should just specialize `IsAoS`.
If I understand correctly, you want: ``` template<class> struct IsComplex_impl {using type = std::false_type;}; template<class T> struct IsComplex_impl<std::complex<T>> {using type = std::true_type;}; template <typename T> using IsComplex = typename IsComplex_impl<T>::type; // Declaration only template<typename T, typename T_isComplex = IsComplex<T>> struct IsAoS; // general case template< typename T > struct IsAoS< T, std::false_type >: std::false_type{}; // specialization for complex<double> template<> struct IsAoS< std::complex<double>>: std::true_type{}; ``` [Live Demo](https://ideone.com/6gNRbW) or with same signature: ``` template<class> struct IsComplex_impl : std::false_type {}; template<class T> struct IsComplex_impl<std::complex<T>> : std::true_type {}; template <typename T> constexpr bool IsComplex() {return IsComplex_impl<T>::value;} // Declaration only template<typename T, bool T_isComplex = IsComplex<T>()> struct IsAoS; // general case template< typename T > struct IsAoS< T, false>: std::false_type{}; // specialization for complex<double> template<> struct IsAoS< std::complex<double>>: std::true_type{}; ``` [Live Demo](https://ideone.com/qQqeax)
34,481,610
I'm working on an iOS app, that should work fine with both iphones and ipads. As I know we can build the app as universal or convert iphone storyboard into ipad storyboard.What I want to know is, what is the best way from these and, when we launch app to app store, is it a problem to have two storyboards one for iphone and another for ipad.
2015/12/27
[ "https://Stackoverflow.com/questions/34481610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5680499/" ]
Your approach is too complicated. You don't need to examine every array element. The first value is `4`, so `7` is *at least* `7-4` elements away, and you can skip those. ``` #include <stdio.h> #include <stdlib.h> int main (void) { int array[] = {4,5,6,5,4,3,2,3,4,5,6,7,8}; int len = sizeof array / sizeof array[0]; int i = 0; int steps = 0; while (i < len && array[i] != 7) { i += abs(7 - array[i]); steps++; } printf("Steps %d, index %d\n", steps, i); return 0; } ``` Program output: ``` Steps 4, index 11 ``` Edit: improved after comments from @Martin Zabel.
A variation of the conventional linear search could be a good way to go. Let us pick an element say `array[i] = 2`. Now, `array[i + 1]` will either be 1 or 3 (odd), `array[i + 2]` will be (positive integers only) 2 or 4 (even number). On continuing like this, a pattern is observable - `array[i + 2*n]` will hold even numbers and so all these indices can be ignored. Also, we can see that ``` array[i + 3] = 1 or 3 or 5 array[i + 5] = 1 or 3 or 5 or 7 ``` so, index `i + 5` should be checked next and a while loop can be used to determine the next index to check, depending on the value found at index `i + 5`. While, this has complexity `O(n)` (linear time in terms of asymptotic complexity), it is better than a normal linear search in practical terms as all the indices are not visited. Obviously, all this will be reversed if `array[i]` (our starting point) was odd.
34,481,610
I'm working on an iOS app, that should work fine with both iphones and ipads. As I know we can build the app as universal or convert iphone storyboard into ipad storyboard.What I want to know is, what is the best way from these and, when we launch app to app store, is it a problem to have two storyboards one for iphone and another for ipad.
2015/12/27
[ "https://Stackoverflow.com/questions/34481610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5680499/" ]
Your approach is too complicated. You don't need to examine every array element. The first value is `4`, so `7` is *at least* `7-4` elements away, and you can skip those. ``` #include <stdio.h> #include <stdlib.h> int main (void) { int array[] = {4,5,6,5,4,3,2,3,4,5,6,7,8}; int len = sizeof array / sizeof array[0]; int i = 0; int steps = 0; while (i < len && array[i] != 7) { i += abs(7 - array[i]); steps++; } printf("Steps %d, index %d\n", steps, i); return 0; } ``` Program output: ``` Steps 4, index 11 ``` Edit: improved after comments from @Martin Zabel.
Here is a divide-and-conquer style solution. At the expense of (much) more bookkeeping, we can skip more elements; rather than scanning left-to-right, test in the middle and skip in *both* directions. ``` #include <stdio.h> #include <math.h> int could_contain(int k, int left, int right, int width); int find(int k, int array[], int lower, int upper); int main(void){ int a[] = {4,3,2,3,2,3,4,5,4,5,6,7,8,7,8}; printf("7 first occurs at index %d\n",find(7,a,0,14)); printf("but 9 first \"occurs\" at index %d\n",find(9,a,0,14)); return 0; } int could_contain(int k, int left, int right, int width){ return (width >= 0) && (left <= k && k <= right) || (right <= k && k <= left) || (abs(k - left) + abs(k - right) < width); } int find(int k, int array[], int lower, int upper){ //printf("%d\t%d\n", lower, upper); if( !could_contain(k, array[lower], array[upper], upper - lower )) return -1; int mid = (upper + lower) / 2; if(array[mid] == k) return mid; lower = find(k, array, lower + abs(k - array[lower]), mid - abs(k - array[mid])); if(lower >= 0 ) return lower; upper = find(k, array, mid + abs(k - array[mid]), upper - abs(k - array[upper])); if(upper >= 0 ) return upper; return -1; } ```
34,481,610
I'm working on an iOS app, that should work fine with both iphones and ipads. As I know we can build the app as universal or convert iphone storyboard into ipad storyboard.What I want to know is, what is the best way from these and, when we launch app to app store, is it a problem to have two storyboards one for iphone and another for ipad.
2015/12/27
[ "https://Stackoverflow.com/questions/34481610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5680499/" ]
You can do a linear search with steps that are often greater than 1. The crucial observation is that if e.g. `array[i] == 4` and 7 hasn't yet appeared then the next candidate for 7 is at index `i+3`. Use a while loop which repeatedly goes directly to the next viable candidate. Here is an implementation, slightly generalized. It finds the first occurrence of `k` in the array (subject to the +=1 restriction) or `-1` if it doesn't occur: ``` #include <stdio.h> #include <stdlib.h> int first_occurence(int k, int array[], int n); int main(void){ int a[] = {4,3,2,3,2,3,4,5,4,5,6,7,8,7,8}; printf("7 first occurs at index %d\n",first_occurence(7,a,15)); printf("but 9 first \"occurs\" at index %d\n",first_occurence(9,a,15)); return 0; } int first_occurence(int k, int array[], int n){ int i = 0; while(i < n){ if(array[i] == k) return i; i += abs(k-array[i]); } return -1; } ``` output: ``` 7 first occurs at index 11 but 9 first "occurs" at index -1 ```
The approach presented by John Coleman is what the interviewer was hoping for, in all probability. If you are willing to go quite a bit more complicated, you can increase expected skip length: Call the target value *k*. Start with the first element's value *v* at position *p* and call the difference k-v *dv* with absolute value *av*. To speed negative searches, have a peek at the last element as the other value *u* at position *o*: if dv×du is negative, k is present (if any occurrence of k is acceptable, you may narrow down the index range here the way binary search does). If av+au is greater than the length of the array, k is absent. (If dv×du is zero, v or u equals k.) Omitting index validity: Probe the ("next") position where the sequence might return to v with k in the middle: `o = p + 2*av`. If dv×du is negative, find k (recursively?) from p+av to o-au; if it is zero, u equals k at o. If du equals dv and the value in the middle isn't k, or au exceeds av, or you *fail* to find k from p+av to o-au, let `p=o; dv=du; av=au;` and keep probing. (For a full flash-back to '60ies texts, view with Courier. My "1st 2nd thought" was to use `o = p + 2*av - 1`, which precludes *du equals dv*.)
34,481,610
I'm working on an iOS app, that should work fine with both iphones and ipads. As I know we can build the app as universal or convert iphone storyboard into ipad storyboard.What I want to know is, what is the best way from these and, when we launch app to app store, is it a problem to have two storyboards one for iphone and another for ipad.
2015/12/27
[ "https://Stackoverflow.com/questions/34481610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5680499/" ]
The approach presented by John Coleman is what the interviewer was hoping for, in all probability. If you are willing to go quite a bit more complicated, you can increase expected skip length: Call the target value *k*. Start with the first element's value *v* at position *p* and call the difference k-v *dv* with absolute value *av*. To speed negative searches, have a peek at the last element as the other value *u* at position *o*: if dv×du is negative, k is present (if any occurrence of k is acceptable, you may narrow down the index range here the way binary search does). If av+au is greater than the length of the array, k is absent. (If dv×du is zero, v or u equals k.) Omitting index validity: Probe the ("next") position where the sequence might return to v with k in the middle: `o = p + 2*av`. If dv×du is negative, find k (recursively?) from p+av to o-au; if it is zero, u equals k at o. If du equals dv and the value in the middle isn't k, or au exceeds av, or you *fail* to find k from p+av to o-au, let `p=o; dv=du; av=au;` and keep probing. (For a full flash-back to '60ies texts, view with Courier. My "1st 2nd thought" was to use `o = p + 2*av - 1`, which precludes *du equals dv*.)
``` const findMeAnElementsFunkyArray = (arr, ele, i) => { const elementAtCurrentIndex = arr[i]; const differenceBetweenEleAndEleAtIndex = Math.abs( ele - elementAtCurrentIndex ); const hop = i + differenceBetweenEleAndEleAtIndex; if (i >= arr.length) { return; } if (arr[i] === ele) { return i; } const result = findMeAnElementsFunkyArray(arr, ele, hop); return result; }; const array = [4,5,6,5,4,3,2,3,4,5,6,7,8]; const answer = findMeAnElementsFunkyArray(array, 7, 0); console.log(answer); ``` Wanted to include a recursive solution to the problem. Enjoy
34,481,610
I'm working on an iOS app, that should work fine with both iphones and ipads. As I know we can build the app as universal or convert iphone storyboard into ipad storyboard.What I want to know is, what is the best way from these and, when we launch app to app store, is it a problem to have two storyboards one for iphone and another for ipad.
2015/12/27
[ "https://Stackoverflow.com/questions/34481610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5680499/" ]
Your approach is too complicated. You don't need to examine every array element. The first value is `4`, so `7` is *at least* `7-4` elements away, and you can skip those. ``` #include <stdio.h> #include <stdlib.h> int main (void) { int array[] = {4,5,6,5,4,3,2,3,4,5,6,7,8}; int len = sizeof array / sizeof array[0]; int i = 0; int steps = 0; while (i < len && array[i] != 7) { i += abs(7 - array[i]); steps++; } printf("Steps %d, index %d\n", steps, i); return 0; } ``` Program output: ``` Steps 4, index 11 ``` Edit: improved after comments from @Martin Zabel.
``` const findMeAnElementsFunkyArray = (arr, ele, i) => { const elementAtCurrentIndex = arr[i]; const differenceBetweenEleAndEleAtIndex = Math.abs( ele - elementAtCurrentIndex ); const hop = i + differenceBetweenEleAndEleAtIndex; if (i >= arr.length) { return; } if (arr[i] === ele) { return i; } const result = findMeAnElementsFunkyArray(arr, ele, hop); return result; }; const array = [4,5,6,5,4,3,2,3,4,5,6,7,8]; const answer = findMeAnElementsFunkyArray(array, 7, 0); console.log(answer); ``` Wanted to include a recursive solution to the problem. Enjoy
34,481,610
I'm working on an iOS app, that should work fine with both iphones and ipads. As I know we can build the app as universal or convert iphone storyboard into ipad storyboard.What I want to know is, what is the best way from these and, when we launch app to app store, is it a problem to have two storyboards one for iphone and another for ipad.
2015/12/27
[ "https://Stackoverflow.com/questions/34481610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5680499/" ]
The approach presented by John Coleman is what the interviewer was hoping for, in all probability. If you are willing to go quite a bit more complicated, you can increase expected skip length: Call the target value *k*. Start with the first element's value *v* at position *p* and call the difference k-v *dv* with absolute value *av*. To speed negative searches, have a peek at the last element as the other value *u* at position *o*: if dv×du is negative, k is present (if any occurrence of k is acceptable, you may narrow down the index range here the way binary search does). If av+au is greater than the length of the array, k is absent. (If dv×du is zero, v or u equals k.) Omitting index validity: Probe the ("next") position where the sequence might return to v with k in the middle: `o = p + 2*av`. If dv×du is negative, find k (recursively?) from p+av to o-au; if it is zero, u equals k at o. If du equals dv and the value in the middle isn't k, or au exceeds av, or you *fail* to find k from p+av to o-au, let `p=o; dv=du; av=au;` and keep probing. (For a full flash-back to '60ies texts, view with Courier. My "1st 2nd thought" was to use `o = p + 2*av - 1`, which precludes *du equals dv*.)
Here is a divide-and-conquer style solution. At the expense of (much) more bookkeeping, we can skip more elements; rather than scanning left-to-right, test in the middle and skip in *both* directions. ``` #include <stdio.h> #include <math.h> int could_contain(int k, int left, int right, int width); int find(int k, int array[], int lower, int upper); int main(void){ int a[] = {4,3,2,3,2,3,4,5,4,5,6,7,8,7,8}; printf("7 first occurs at index %d\n",find(7,a,0,14)); printf("but 9 first \"occurs\" at index %d\n",find(9,a,0,14)); return 0; } int could_contain(int k, int left, int right, int width){ return (width >= 0) && (left <= k && k <= right) || (right <= k && k <= left) || (abs(k - left) + abs(k - right) < width); } int find(int k, int array[], int lower, int upper){ //printf("%d\t%d\n", lower, upper); if( !could_contain(k, array[lower], array[upper], upper - lower )) return -1; int mid = (upper + lower) / 2; if(array[mid] == k) return mid; lower = find(k, array, lower + abs(k - array[lower]), mid - abs(k - array[mid])); if(lower >= 0 ) return lower; upper = find(k, array, mid + abs(k - array[mid]), upper - abs(k - array[upper])); if(upper >= 0 ) return upper; return -1; } ```
34,481,610
I'm working on an iOS app, that should work fine with both iphones and ipads. As I know we can build the app as universal or convert iphone storyboard into ipad storyboard.What I want to know is, what is the best way from these and, when we launch app to app store, is it a problem to have two storyboards one for iphone and another for ipad.
2015/12/27
[ "https://Stackoverflow.com/questions/34481610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5680499/" ]
The approach presented by John Coleman is what the interviewer was hoping for, in all probability. If you are willing to go quite a bit more complicated, you can increase expected skip length: Call the target value *k*. Start with the first element's value *v* at position *p* and call the difference k-v *dv* with absolute value *av*. To speed negative searches, have a peek at the last element as the other value *u* at position *o*: if dv×du is negative, k is present (if any occurrence of k is acceptable, you may narrow down the index range here the way binary search does). If av+au is greater than the length of the array, k is absent. (If dv×du is zero, v or u equals k.) Omitting index validity: Probe the ("next") position where the sequence might return to v with k in the middle: `o = p + 2*av`. If dv×du is negative, find k (recursively?) from p+av to o-au; if it is zero, u equals k at o. If du equals dv and the value in the middle isn't k, or au exceeds av, or you *fail* to find k from p+av to o-au, let `p=o; dv=du; av=au;` and keep probing. (For a full flash-back to '60ies texts, view with Courier. My "1st 2nd thought" was to use `o = p + 2*av - 1`, which precludes *du equals dv*.)
**STEP 1** Start with the first element and check if it's 7. Let's say `c` is the index of the current position. So, initially, `c = 0`. **STEP 2** If it is 7, you found the index. It's `c`. If you've reached the end of the array, break out. **STEP 3** If it's not, then 7 must be atleast `|array[c]-7|` positions away because you can only add a unit per index. Therefore, Add `|array[c]-7|` to your current index, c, and go to STEP 2 again to check. In the worst case, when there are alternate 1 and -1s, the time complexity may reach O(n), but average cases would be delivered quickly.
34,481,610
I'm working on an iOS app, that should work fine with both iphones and ipads. As I know we can build the app as universal or convert iphone storyboard into ipad storyboard.What I want to know is, what is the best way from these and, when we launch app to app store, is it a problem to have two storyboards one for iphone and another for ipad.
2015/12/27
[ "https://Stackoverflow.com/questions/34481610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5680499/" ]
A variation of the conventional linear search could be a good way to go. Let us pick an element say `array[i] = 2`. Now, `array[i + 1]` will either be 1 or 3 (odd), `array[i + 2]` will be (positive integers only) 2 or 4 (even number). On continuing like this, a pattern is observable - `array[i + 2*n]` will hold even numbers and so all these indices can be ignored. Also, we can see that ``` array[i + 3] = 1 or 3 or 5 array[i + 5] = 1 or 3 or 5 or 7 ``` so, index `i + 5` should be checked next and a while loop can be used to determine the next index to check, depending on the value found at index `i + 5`. While, this has complexity `O(n)` (linear time in terms of asymptotic complexity), it is better than a normal linear search in practical terms as all the indices are not visited. Obviously, all this will be reversed if `array[i]` (our starting point) was odd.
``` const findMeAnElementsFunkyArray = (arr, ele, i) => { const elementAtCurrentIndex = arr[i]; const differenceBetweenEleAndEleAtIndex = Math.abs( ele - elementAtCurrentIndex ); const hop = i + differenceBetweenEleAndEleAtIndex; if (i >= arr.length) { return; } if (arr[i] === ele) { return i; } const result = findMeAnElementsFunkyArray(arr, ele, hop); return result; }; const array = [4,5,6,5,4,3,2,3,4,5,6,7,8]; const answer = findMeAnElementsFunkyArray(array, 7, 0); console.log(answer); ``` Wanted to include a recursive solution to the problem. Enjoy
34,481,610
I'm working on an iOS app, that should work fine with both iphones and ipads. As I know we can build the app as universal or convert iphone storyboard into ipad storyboard.What I want to know is, what is the best way from these and, when we launch app to app store, is it a problem to have two storyboards one for iphone and another for ipad.
2015/12/27
[ "https://Stackoverflow.com/questions/34481610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5680499/" ]
You can do a linear search with steps that are often greater than 1. The crucial observation is that if e.g. `array[i] == 4` and 7 hasn't yet appeared then the next candidate for 7 is at index `i+3`. Use a while loop which repeatedly goes directly to the next viable candidate. Here is an implementation, slightly generalized. It finds the first occurrence of `k` in the array (subject to the +=1 restriction) or `-1` if it doesn't occur: ``` #include <stdio.h> #include <stdlib.h> int first_occurence(int k, int array[], int n); int main(void){ int a[] = {4,3,2,3,2,3,4,5,4,5,6,7,8,7,8}; printf("7 first occurs at index %d\n",first_occurence(7,a,15)); printf("but 9 first \"occurs\" at index %d\n",first_occurence(9,a,15)); return 0; } int first_occurence(int k, int array[], int n){ int i = 0; while(i < n){ if(array[i] == k) return i; i += abs(k-array[i]); } return -1; } ``` output: ``` 7 first occurs at index 11 but 9 first "occurs" at index -1 ```
A variation of the conventional linear search could be a good way to go. Let us pick an element say `array[i] = 2`. Now, `array[i + 1]` will either be 1 or 3 (odd), `array[i + 2]` will be (positive integers only) 2 or 4 (even number). On continuing like this, a pattern is observable - `array[i + 2*n]` will hold even numbers and so all these indices can be ignored. Also, we can see that ``` array[i + 3] = 1 or 3 or 5 array[i + 5] = 1 or 3 or 5 or 7 ``` so, index `i + 5` should be checked next and a while loop can be used to determine the next index to check, depending on the value found at index `i + 5`. While, this has complexity `O(n)` (linear time in terms of asymptotic complexity), it is better than a normal linear search in practical terms as all the indices are not visited. Obviously, all this will be reversed if `array[i]` (our starting point) was odd.
34,481,610
I'm working on an iOS app, that should work fine with both iphones and ipads. As I know we can build the app as universal or convert iphone storyboard into ipad storyboard.What I want to know is, what is the best way from these and, when we launch app to app store, is it a problem to have two storyboards one for iphone and another for ipad.
2015/12/27
[ "https://Stackoverflow.com/questions/34481610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5680499/" ]
You can do a linear search with steps that are often greater than 1. The crucial observation is that if e.g. `array[i] == 4` and 7 hasn't yet appeared then the next candidate for 7 is at index `i+3`. Use a while loop which repeatedly goes directly to the next viable candidate. Here is an implementation, slightly generalized. It finds the first occurrence of `k` in the array (subject to the +=1 restriction) or `-1` if it doesn't occur: ``` #include <stdio.h> #include <stdlib.h> int first_occurence(int k, int array[], int n); int main(void){ int a[] = {4,3,2,3,2,3,4,5,4,5,6,7,8,7,8}; printf("7 first occurs at index %d\n",first_occurence(7,a,15)); printf("but 9 first \"occurs\" at index %d\n",first_occurence(9,a,15)); return 0; } int first_occurence(int k, int array[], int n){ int i = 0; while(i < n){ if(array[i] == k) return i; i += abs(k-array[i]); } return -1; } ``` output: ``` 7 first occurs at index 11 but 9 first "occurs" at index -1 ```
Here is a divide-and-conquer style solution. At the expense of (much) more bookkeeping, we can skip more elements; rather than scanning left-to-right, test in the middle and skip in *both* directions. ``` #include <stdio.h> #include <math.h> int could_contain(int k, int left, int right, int width); int find(int k, int array[], int lower, int upper); int main(void){ int a[] = {4,3,2,3,2,3,4,5,4,5,6,7,8,7,8}; printf("7 first occurs at index %d\n",find(7,a,0,14)); printf("but 9 first \"occurs\" at index %d\n",find(9,a,0,14)); return 0; } int could_contain(int k, int left, int right, int width){ return (width >= 0) && (left <= k && k <= right) || (right <= k && k <= left) || (abs(k - left) + abs(k - right) < width); } int find(int k, int array[], int lower, int upper){ //printf("%d\t%d\n", lower, upper); if( !could_contain(k, array[lower], array[upper], upper - lower )) return -1; int mid = (upper + lower) / 2; if(array[mid] == k) return mid; lower = find(k, array, lower + abs(k - array[lower]), mid - abs(k - array[mid])); if(lower >= 0 ) return lower; upper = find(k, array, mid + abs(k - array[mid]), upper - abs(k - array[upper])); if(upper >= 0 ) return upper; return -1; } ```
698,478
I have to run Mac OS on virtual box for a class and it keeps giving me errors stating "VT-x/AMD-V hardware acceleration not available on your system. Certain guests (e.g. OS/2 and QNX) require this feature and will fail to boot without it." If there is a solution, I am not used to windows 8.1 and will need detailed instructions on how to fix it. Thank you
2014/01/08
[ "https://superuser.com/questions/698478", "https://superuser.com", "https://superuser.com/users/287753/" ]
Do you have Hyper-V installed? For example it may have been added if you installed the Windows Phone emulators which come with Visual Studio 2012 & 2013. If so, then there is a known conflict between Hyper-V and VirtualBox - [Hardware Virtualisation support not detected if Hyper-V installed](https://www.virtualbox.org/ticket/12350). A similar problem occurs trying to use Intel HAXM to accelerate Android x86 Virtual Devices - [Windows 8 - How to install Intel HAXM after installing Hyper-V](http://forums.ouya.tv/discussion/82/windows-8-how-to-install-intel-haxm-after-installing-hyper-v). Uninstalling the Windows Phone emulators and turning Hyper-V off in `Control Panel >> Programs and Features >> Turn Windows features on or off` seems to be the only workaround for the moment.
As previous replies have said, check if your processor supports VT-x virtualization. If it doesn't, then you just won't be able to run Mac OS on VirtualBox. If that is the case, consider VMWare Player, which is a decent alternative for VirtualBox, and is also free. It is commonly used in computers whose processors don't support VT-x to emulate Mac OS.
698,478
I have to run Mac OS on virtual box for a class and it keeps giving me errors stating "VT-x/AMD-V hardware acceleration not available on your system. Certain guests (e.g. OS/2 and QNX) require this feature and will fail to boot without it." If there is a solution, I am not used to windows 8.1 and will need detailed instructions on how to fix it. Thank you
2014/01/08
[ "https://superuser.com/questions/698478", "https://superuser.com", "https://superuser.com/users/287753/" ]
***You don't have to uninstall/reinstall HyperV*** I ran into this same issue using the new Visual Studio 2015 Android emulator and Windows Phone emulator, while also trying to run VirtualBox clients. Unfortunately you can't run VBox at the same time as the other emulators; you just have to setup a new boot option and reboot to switch back and forth. Open an administrative command prompt and run: ``` C:\>bcdedit /copy {current} /d "Windows w/ HyperV" C:\>bcdedit /set hypervisorlaunchtype off ``` This will copy your current boot settings to a new boot option called "Windows w/ HyperV" and then will disable HyperV under your current boot option. You can run "bcdedit" with no parameters to check that {current} has the hypvervisorlaunchtype set to "off" and that the new section has hypvervisorlaunchtype set to "auto" See [Scott Hanselman's article](http://www.hanselman.com/blog/SwitchEasilyBetweenVirtualBoxAndHyperVWithABCDEditBootEntryInWindows81.aspx) for more information.
As previous replies have said, check if your processor supports VT-x virtualization. If it doesn't, then you just won't be able to run Mac OS on VirtualBox. If that is the case, consider VMWare Player, which is a decent alternative for VirtualBox, and is also free. It is commonly used in computers whose processors don't support VT-x to emulate Mac OS.
698,478
I have to run Mac OS on virtual box for a class and it keeps giving me errors stating "VT-x/AMD-V hardware acceleration not available on your system. Certain guests (e.g. OS/2 and QNX) require this feature and will fail to boot without it." If there is a solution, I am not used to windows 8.1 and will need detailed instructions on how to fix it. Thank you
2014/01/08
[ "https://superuser.com/questions/698478", "https://superuser.com", "https://superuser.com/users/287753/" ]
For anyone else who may look this up in future. I had the same problem. Turns out virtualization had been disabled in the bios. Check if this is the case. If so, just enable it and the error is gone
As previous replies have said, check if your processor supports VT-x virtualization. If it doesn't, then you just won't be able to run Mac OS on VirtualBox. If that is the case, consider VMWare Player, which is a decent alternative for VirtualBox, and is also free. It is commonly used in computers whose processors don't support VT-x to emulate Mac OS.
698,478
I have to run Mac OS on virtual box for a class and it keeps giving me errors stating "VT-x/AMD-V hardware acceleration not available on your system. Certain guests (e.g. OS/2 and QNX) require this feature and will fail to boot without it." If there is a solution, I am not used to windows 8.1 and will need detailed instructions on how to fix it. Thank you
2014/01/08
[ "https://superuser.com/questions/698478", "https://superuser.com", "https://superuser.com/users/287753/" ]
Do you have Hyper-V installed? For example it may have been added if you installed the Windows Phone emulators which come with Visual Studio 2012 & 2013. If so, then there is a known conflict between Hyper-V and VirtualBox - [Hardware Virtualisation support not detected if Hyper-V installed](https://www.virtualbox.org/ticket/12350). A similar problem occurs trying to use Intel HAXM to accelerate Android x86 Virtual Devices - [Windows 8 - How to install Intel HAXM after installing Hyper-V](http://forums.ouya.tv/discussion/82/windows-8-how-to-install-intel-haxm-after-installing-hyper-v). Uninstalling the Windows Phone emulators and turning Hyper-V off in `Control Panel >> Programs and Features >> Turn Windows features on or off` seems to be the only workaround for the moment.
For anyone else who may look this up in future. I had the same problem. Turns out virtualization had been disabled in the bios. Check if this is the case. If so, just enable it and the error is gone
698,478
I have to run Mac OS on virtual box for a class and it keeps giving me errors stating "VT-x/AMD-V hardware acceleration not available on your system. Certain guests (e.g. OS/2 and QNX) require this feature and will fail to boot without it." If there is a solution, I am not used to windows 8.1 and will need detailed instructions on how to fix it. Thank you
2014/01/08
[ "https://superuser.com/questions/698478", "https://superuser.com", "https://superuser.com/users/287753/" ]
***You don't have to uninstall/reinstall HyperV*** I ran into this same issue using the new Visual Studio 2015 Android emulator and Windows Phone emulator, while also trying to run VirtualBox clients. Unfortunately you can't run VBox at the same time as the other emulators; you just have to setup a new boot option and reboot to switch back and forth. Open an administrative command prompt and run: ``` C:\>bcdedit /copy {current} /d "Windows w/ HyperV" C:\>bcdedit /set hypervisorlaunchtype off ``` This will copy your current boot settings to a new boot option called "Windows w/ HyperV" and then will disable HyperV under your current boot option. You can run "bcdedit" with no parameters to check that {current} has the hypvervisorlaunchtype set to "off" and that the new section has hypvervisorlaunchtype set to "auto" See [Scott Hanselman's article](http://www.hanselman.com/blog/SwitchEasilyBetweenVirtualBoxAndHyperVWithABCDEditBootEntryInWindows81.aspx) for more information.
For anyone else who may look this up in future. I had the same problem. Turns out virtualization had been disabled in the bios. Check if this is the case. If so, just enable it and the error is gone
10,315,793
Okay, you may call me a noob but I'm realling confused. My ex classmate paid me to write a program in C. She gave me the task and it said something like "blah blah blah make at least TWO CLASSES, write at least ONE CONSTRUCTOR and rewrite at least ONE METHOD" it says that word by word. And then I told her "this is C++ not C" she said "but we're learning C" I ignored it and wrote the program in c++ and sent to her as I thought she didn't know what she was talking about. She said "it doesn't work on code blocks, and wtf is cout <<" and then she sent me a chunk of code that they write and instead of cout and cin there was printf and scanf. It had to be C. So, I rewrote the program with printf and scanf and she still says codeblocks throw errors (I still left classes as task demanded). I want to ask wtf? Does C have classes? Or is there a misunderstanding or something? EDIT: I've come back to the question after so many years and noticed some a\*\*\*\*\*es took time to remove 99% text from the question. Get a life, this is not 1984 yet.
2012/04/25
[ "https://Stackoverflow.com/questions/10315793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1289097/" ]
C doesn't support classes, but we do have **tricky hacky workaround**. Read entire explanation or simply scroll down to code section. struct declaration: ------------------- I declared an `struct` with name **class**. Inside, I put uninitialized `function` with type **void**, name **Print** and one parameter **char**. This will look like `void class.Print(char);` struct don't allow initialization inside: ----------------------------------------- But struct doesn't allow initialization of variables inside. So we will init it outside. We created an a `function` with type of **class**, name **Printer**. It inits that `struct` and return initialized struct which we can easily make use of. call the class: --------------- Now we included helper header and declared variable with type `class`, name `printer1`, value `Printer()`. After I called member of class and print string using `printer1.Print("Hello from class function");` `main.c` ```cpp #include "helper.h" void main() { class printer1 = Printer(); printer1.Print("Hello from class function"); } ``` `helper.h` ```cpp #include <stdio.h> //imports int printf(...); void print(const char* text) { printf(text); } typedef struct { void (*Print) (const char*); } class; class Printer() { class Printer; Printer.Print = &print; return Printer; } ``` **Note:** * This exact example was compiled and tested successfully with VC and tcc compiler. * `class` is example name. You can use any other name as well.
C mostly uses functional/structural programming instead of implementing Object Oriented Programming as in languages like C++ , Java , Python etc. which use classes . But in few instances we use classes like in: ```c typedef struct { ShapeClass shape; float width, height; } RectangleClass; ``` Hope it helped.
10,315,793
Okay, you may call me a noob but I'm realling confused. My ex classmate paid me to write a program in C. She gave me the task and it said something like "blah blah blah make at least TWO CLASSES, write at least ONE CONSTRUCTOR and rewrite at least ONE METHOD" it says that word by word. And then I told her "this is C++ not C" she said "but we're learning C" I ignored it and wrote the program in c++ and sent to her as I thought she didn't know what she was talking about. She said "it doesn't work on code blocks, and wtf is cout <<" and then she sent me a chunk of code that they write and instead of cout and cin there was printf and scanf. It had to be C. So, I rewrote the program with printf and scanf and she still says codeblocks throw errors (I still left classes as task demanded). I want to ask wtf? Does C have classes? Or is there a misunderstanding or something? EDIT: I've come back to the question after so many years and noticed some a\*\*\*\*\*es took time to remove 99% text from the question. Get a life, this is not 1984 yet.
2012/04/25
[ "https://Stackoverflow.com/questions/10315793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1289097/" ]
No, C doesn't have classes. That said, there are ways of simulating object-oriented programming in C - a quick Google search should yield some useful results.
A classic case of conflicting requirements, it seems :-) The terminology of her requirements *CLASS, CONSTRUCTOR, METHOD* are all C++ terminology, while none of them is C terminology (the closest of which would arguably be *STRUCT, INITIALIZATION, FUNCTION*). Your friend **is** confusing something here. I doubt that her teacher is confusing something, though...
10,315,793
Okay, you may call me a noob but I'm realling confused. My ex classmate paid me to write a program in C. She gave me the task and it said something like "blah blah blah make at least TWO CLASSES, write at least ONE CONSTRUCTOR and rewrite at least ONE METHOD" it says that word by word. And then I told her "this is C++ not C" she said "but we're learning C" I ignored it and wrote the program in c++ and sent to her as I thought she didn't know what she was talking about. She said "it doesn't work on code blocks, and wtf is cout <<" and then she sent me a chunk of code that they write and instead of cout and cin there was printf and scanf. It had to be C. So, I rewrote the program with printf and scanf and she still says codeblocks throw errors (I still left classes as task demanded). I want to ask wtf? Does C have classes? Or is there a misunderstanding or something? EDIT: I've come back to the question after so many years and noticed some a\*\*\*\*\*es took time to remove 99% text from the question. Get a life, this is not 1984 yet.
2012/04/25
[ "https://Stackoverflow.com/questions/10315793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1289097/" ]
No, C doesn't have classes. That said, there are ways of simulating object-oriented programming in C - a quick Google search should yield some useful results.
C does not have classes. But one can approximate a class by using static globals as private class members, and static functions as private member functions. extern members as public. In this case an entire file could be viewed as a class. Probably this is not what you want.
10,315,793
Okay, you may call me a noob but I'm realling confused. My ex classmate paid me to write a program in C. She gave me the task and it said something like "blah blah blah make at least TWO CLASSES, write at least ONE CONSTRUCTOR and rewrite at least ONE METHOD" it says that word by word. And then I told her "this is C++ not C" she said "but we're learning C" I ignored it and wrote the program in c++ and sent to her as I thought she didn't know what she was talking about. She said "it doesn't work on code blocks, and wtf is cout <<" and then she sent me a chunk of code that they write and instead of cout and cin there was printf and scanf. It had to be C. So, I rewrote the program with printf and scanf and she still says codeblocks throw errors (I still left classes as task demanded). I want to ask wtf? Does C have classes? Or is there a misunderstanding or something? EDIT: I've come back to the question after so many years and noticed some a\*\*\*\*\*es took time to remove 99% text from the question. Get a life, this is not 1984 yet.
2012/04/25
[ "https://Stackoverflow.com/questions/10315793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1289097/" ]
C does not have the formal construct of a class. You can produce modules with module-level data that by your own agreement you will not extern anywhere else, or static data, and write functions to get, set, and otherwise manipulate that data. You can even go to the point of using function pointers to manipulate similar data types as if they were in a class. However, you won't be protected by class semantics or other rules by the C compiler, because the C compiler does not know about classes. However, structuring your data is quite powerful.
C mostly uses functional/structural programming instead of implementing Object Oriented Programming as in languages like C++ , Java , Python etc. which use classes . But in few instances we use classes like in: ```c typedef struct { ShapeClass shape; float width, height; } RectangleClass; ``` Hope it helped.
10,315,793
Okay, you may call me a noob but I'm realling confused. My ex classmate paid me to write a program in C. She gave me the task and it said something like "blah blah blah make at least TWO CLASSES, write at least ONE CONSTRUCTOR and rewrite at least ONE METHOD" it says that word by word. And then I told her "this is C++ not C" she said "but we're learning C" I ignored it and wrote the program in c++ and sent to her as I thought she didn't know what she was talking about. She said "it doesn't work on code blocks, and wtf is cout <<" and then she sent me a chunk of code that they write and instead of cout and cin there was printf and scanf. It had to be C. So, I rewrote the program with printf and scanf and she still says codeblocks throw errors (I still left classes as task demanded). I want to ask wtf? Does C have classes? Or is there a misunderstanding or something? EDIT: I've come back to the question after so many years and noticed some a\*\*\*\*\*es took time to remove 99% text from the question. Get a life, this is not 1984 yet.
2012/04/25
[ "https://Stackoverflow.com/questions/10315793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1289097/" ]
No, C doesn't have classes. That said, there are ways of simulating object-oriented programming in C - a quick Google search should yield some useful results.
C does not have classes, but you can emulate it with structures and pointers to a function. C99 is a little bit (just a bit) based on C++, so it's easy to reproduce classes with C.
10,315,793
Okay, you may call me a noob but I'm realling confused. My ex classmate paid me to write a program in C. She gave me the task and it said something like "blah blah blah make at least TWO CLASSES, write at least ONE CONSTRUCTOR and rewrite at least ONE METHOD" it says that word by word. And then I told her "this is C++ not C" she said "but we're learning C" I ignored it and wrote the program in c++ and sent to her as I thought she didn't know what she was talking about. She said "it doesn't work on code blocks, and wtf is cout <<" and then she sent me a chunk of code that they write and instead of cout and cin there was printf and scanf. It had to be C. So, I rewrote the program with printf and scanf and she still says codeblocks throw errors (I still left classes as task demanded). I want to ask wtf? Does C have classes? Or is there a misunderstanding or something? EDIT: I've come back to the question after so many years and noticed some a\*\*\*\*\*es took time to remove 99% text from the question. Get a life, this is not 1984 yet.
2012/04/25
[ "https://Stackoverflow.com/questions/10315793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1289097/" ]
No, C has no classes per se, only C++ (which started out as "C with classes" back then...). But you can use the standard C library in C++ code, even if it is often not considered good practice (where C++ has its own, higher level constructs, e.g. `cout` vs `printf`). You can sort of emulate the behaviour of classes, inheritance and virtual functions in C too, but it's not worth the pain. You should probably buy/get your ex classmate a C programming book :-)
C does not have classes. But one can approximate a class by using static globals as private class members, and static functions as private member functions. extern members as public. In this case an entire file could be viewed as a class. Probably this is not what you want.
10,315,793
Okay, you may call me a noob but I'm realling confused. My ex classmate paid me to write a program in C. She gave me the task and it said something like "blah blah blah make at least TWO CLASSES, write at least ONE CONSTRUCTOR and rewrite at least ONE METHOD" it says that word by word. And then I told her "this is C++ not C" she said "but we're learning C" I ignored it and wrote the program in c++ and sent to her as I thought she didn't know what she was talking about. She said "it doesn't work on code blocks, and wtf is cout <<" and then she sent me a chunk of code that they write and instead of cout and cin there was printf and scanf. It had to be C. So, I rewrote the program with printf and scanf and she still says codeblocks throw errors (I still left classes as task demanded). I want to ask wtf? Does C have classes? Or is there a misunderstanding or something? EDIT: I've come back to the question after so many years and noticed some a\*\*\*\*\*es took time to remove 99% text from the question. Get a life, this is not 1984 yet.
2012/04/25
[ "https://Stackoverflow.com/questions/10315793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1289097/" ]
No, C doesn't have classes. That said, there are ways of simulating object-oriented programming in C - a quick Google search should yield some useful results.
C mostly uses functional/structural programming instead of implementing Object Oriented Programming as in languages like C++ , Java , Python etc. which use classes . But in few instances we use classes like in: ```c typedef struct { ShapeClass shape; float width, height; } RectangleClass; ``` Hope it helped.
10,315,793
Okay, you may call me a noob but I'm realling confused. My ex classmate paid me to write a program in C. She gave me the task and it said something like "blah blah blah make at least TWO CLASSES, write at least ONE CONSTRUCTOR and rewrite at least ONE METHOD" it says that word by word. And then I told her "this is C++ not C" she said "but we're learning C" I ignored it and wrote the program in c++ and sent to her as I thought she didn't know what she was talking about. She said "it doesn't work on code blocks, and wtf is cout <<" and then she sent me a chunk of code that they write and instead of cout and cin there was printf and scanf. It had to be C. So, I rewrote the program with printf and scanf and she still says codeblocks throw errors (I still left classes as task demanded). I want to ask wtf? Does C have classes? Or is there a misunderstanding or something? EDIT: I've come back to the question after so many years and noticed some a\*\*\*\*\*es took time to remove 99% text from the question. Get a life, this is not 1984 yet.
2012/04/25
[ "https://Stackoverflow.com/questions/10315793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1289097/" ]
No, C has no classes per se, only C++ (which started out as "C with classes" back then...). But you can use the standard C library in C++ code, even if it is often not considered good practice (where C++ has its own, higher level constructs, e.g. `cout` vs `printf`). You can sort of emulate the behaviour of classes, inheritance and virtual functions in C too, but it's not worth the pain. You should probably buy/get your ex classmate a C programming book :-)
C mostly uses functional/structural programming instead of implementing Object Oriented Programming as in languages like C++ , Java , Python etc. which use classes . But in few instances we use classes like in: ```c typedef struct { ShapeClass shape; float width, height; } RectangleClass; ``` Hope it helped.
10,315,793
Okay, you may call me a noob but I'm realling confused. My ex classmate paid me to write a program in C. She gave me the task and it said something like "blah blah blah make at least TWO CLASSES, write at least ONE CONSTRUCTOR and rewrite at least ONE METHOD" it says that word by word. And then I told her "this is C++ not C" she said "but we're learning C" I ignored it and wrote the program in c++ and sent to her as I thought she didn't know what she was talking about. She said "it doesn't work on code blocks, and wtf is cout <<" and then she sent me a chunk of code that they write and instead of cout and cin there was printf and scanf. It had to be C. So, I rewrote the program with printf and scanf and she still says codeblocks throw errors (I still left classes as task demanded). I want to ask wtf? Does C have classes? Or is there a misunderstanding or something? EDIT: I've come back to the question after so many years and noticed some a\*\*\*\*\*es took time to remove 99% text from the question. Get a life, this is not 1984 yet.
2012/04/25
[ "https://Stackoverflow.com/questions/10315793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1289097/" ]
No, C doesn't have classes. That said, there are ways of simulating object-oriented programming in C - a quick Google search should yield some useful results.
C doesn't support classes, but we do have **tricky hacky workaround**. Read entire explanation or simply scroll down to code section. struct declaration: ------------------- I declared an `struct` with name **class**. Inside, I put uninitialized `function` with type **void**, name **Print** and one parameter **char**. This will look like `void class.Print(char);` struct don't allow initialization inside: ----------------------------------------- But struct doesn't allow initialization of variables inside. So we will init it outside. We created an a `function` with type of **class**, name **Printer**. It inits that `struct` and return initialized struct which we can easily make use of. call the class: --------------- Now we included helper header and declared variable with type `class`, name `printer1`, value `Printer()`. After I called member of class and print string using `printer1.Print("Hello from class function");` `main.c` ```cpp #include "helper.h" void main() { class printer1 = Printer(); printer1.Print("Hello from class function"); } ``` `helper.h` ```cpp #include <stdio.h> //imports int printf(...); void print(const char* text) { printf(text); } typedef struct { void (*Print) (const char*); } class; class Printer() { class Printer; Printer.Print = &print; return Printer; } ``` **Note:** * This exact example was compiled and tested successfully with VC and tcc compiler. * `class` is example name. You can use any other name as well.
10,315,793
Okay, you may call me a noob but I'm realling confused. My ex classmate paid me to write a program in C. She gave me the task and it said something like "blah blah blah make at least TWO CLASSES, write at least ONE CONSTRUCTOR and rewrite at least ONE METHOD" it says that word by word. And then I told her "this is C++ not C" she said "but we're learning C" I ignored it and wrote the program in c++ and sent to her as I thought she didn't know what she was talking about. She said "it doesn't work on code blocks, and wtf is cout <<" and then she sent me a chunk of code that they write and instead of cout and cin there was printf and scanf. It had to be C. So, I rewrote the program with printf and scanf and she still says codeblocks throw errors (I still left classes as task demanded). I want to ask wtf? Does C have classes? Or is there a misunderstanding or something? EDIT: I've come back to the question after so many years and noticed some a\*\*\*\*\*es took time to remove 99% text from the question. Get a life, this is not 1984 yet.
2012/04/25
[ "https://Stackoverflow.com/questions/10315793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1289097/" ]
C does not have classes. But one can approximate a class by using static globals as private class members, and static functions as private member functions. extern members as public. In this case an entire file could be viewed as a class. Probably this is not what you want.
C mostly uses functional/structural programming instead of implementing Object Oriented Programming as in languages like C++ , Java , Python etc. which use classes . But in few instances we use classes like in: ```c typedef struct { ShapeClass shape; float width, height; } RectangleClass; ``` Hope it helped.
80,774
I recently switched to a new PC at work, one with two (identical, Dell 23") monitors. I'm running Linux Mint 15 64bit / Cinnamon. Is there a way to set it up in such a way that, instead of both monitors sharing the same huge workspace, they are on separate smaller ones? E.g. left monitor on workspace 1, right monitor on workspace 2, and I could switch either monitor to workspace 3 if needed? Failing that, is there a way to duplicate the bottom panel onto the second monitor? Currently it is only displayed on the left one.
2013/06/26
[ "https://unix.stackexchange.com/questions/80774", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/41904/" ]
Short answer: yes, you can do this. I have my (Fedora) desktop set up this way, each monitor is an independent display. It is the same 'desktop', in the X sense, but there are some limitations to typical desktop functionality with this setup versus the 'single desktop spread over two monitors' configuration. [For example, you can't drag a window from one monitor to the other, or even drag a file from a folder on one monitor and drop it in a folder displayed on the other monitor.] Still, I prefer independent displays. For me it is natural to cycle workspaces on one monitor independently of the workspace displayed on the other monitor. I will warn you - some people are pretty zealous about which way is the 'correct way', so prepare to wade through a lot of noise and ranting if you research how to do what you want to do. I have had many people dismiss my efforts to achieve this setup because they felt it was pointless and "no sane person would want things to work that way". As another user has pointed out, some desktop environments support independent displays and others do not. I was happily using Gnome as my desktop, for ten years or more, until the 3.0 series of Gnome (which lost the capability to support independent X displays on a single desktop ... and it appears that the Gnome development community do not have an interest in resurrecting this capability). Earlier versions of Cinnamon Desktop had this capability, but with Fedora 19 or 20 I can longer achieve it with Cinnamon. I am stuck with Xfce at the moment. In order to achieve independent X displays, I had to carefully craft an xorg.conf file. For my hardware, using the proprietary nvidia driver, the key seems to be to identify multiple Devices using the same BusID, but to then use the 'metamodes' option for each Screen section to uniquely identify the port associated with each monitor in your setup. Here is my xorg.conf: ``` Section "ServerLayout" Identifier "Layout0" Screen 0 "Screen0" 0 0 Screen 1 "Screen1" RightOf "Screen0" InputDevice "Keyboard0" "CoreKeyboard" InputDevice "Mouse0" "CorePointer" Option "Xinerama" "0" EndSection Section "Files" FontPath "/usr/share/fonts/default/Type1" EndSection Section "InputDevice" # generated from default Identifier "Mouse0" Driver "mouse" Option "Protocol" "auto" Option "Device" "/dev/input/mice" Option "Emulate3Buttons" "no" Option "ZAxisMapping" "4 5" EndSection Section "InputDevice" # generated from default Identifier "Keyboard0" Driver "kbd" EndSection Section "Monitor" Identifier "Monitor0" VendorName "DELL" ModelName "P2411Hb" HorizSync 28.0 - 33.0 VertRefresh 43.0 - 72.0 Option "DPMS" EndSection Section "Device" Identifier "Device0" Driver "nvidia" VendorName "NVIDIA Corporation" BoardName "Quadro K2000M" BusID "PCI:1:0:0" Screen 0 EndSection Section "Screen" Identifier "Screen0" Device "Device0" Monitor "Monitor0" Option "TwinView" "0" Option "metamodes" "DFP-0: nvidia-auto-select +0+0" DefaultDepth 24 SubSection "Display" Depth 24 EndSubSection EndSection Section "Monitor" Identifier "Monitor1" VendorName "DELL" ModelName "P2411Hb" HorizSync 28.0 - 33.0 VertRefresh 43.0 - 72.0 Option "DPMS" EndSection Section "Device" Identifier "Device1" Driver "nvidia" VendorName "NVIDIA Corporation" BoardName "Quadro K2000M" BusID "PCI:1:0:0" Screen 1 EndSection Section "Screen" Identifier "Screen1" Device "Device1" Monitor "Monitor1" Option "TwinView" "0" Option "metamodes" "DFP-2: nvidia-auto-select +0+0" DefaultDepth 24 SubSection "Display" Depth 24 EndSubSection EndSection ``` Hopefully that gets you started. I have not found a gui tool in any Desktop Environment that reliably creates an xorg.conf supporting independent displays. My advice is to start with any 'X configuration generator' tool that comes with your chosen video driver (for example, nvidia's `nvidia-xconfig`) and see if you can use my example, above, to guide your trial-and-error.
Found this on the Ubuntu Forums in a thread titled: [gnome panels on two monitors](http://ubuntuforums.org/showthread.php?t=1417900). *excerpt* I believe what you want is the following: 1. You have to right click the panels on Monitor #1 and choose "New Panel" 2. Then hold Alt and click and drag the new panel to Monitor #2. **NOTE:** "Expanded" Panels always "cling" to the edges of your physical screens and hence are unable to span across 2 monitors, this is by design. I believe all of the dual head screenshots that appear to have 2 panels stretched across are just clever layouts of 4 separate panels. ### Issue with MATE? I also came across this ticket in the Linux Mint issue tracker, which to summarize is saying that currently in MATE this feature isn't available. * [Taskbar on second monitor](https://github.com/linuxmint/Cinnamon/issues/130) ### References * [Create new panel on second monitor](http://scott.cm/create-new-panel-on-second-monitor/) * [Adding the panel to the second monitor](https://unix.stackexchange.com/questions/56523/adding-the-panel-to-the-second-monitor)
80,774
I recently switched to a new PC at work, one with two (identical, Dell 23") monitors. I'm running Linux Mint 15 64bit / Cinnamon. Is there a way to set it up in such a way that, instead of both monitors sharing the same huge workspace, they are on separate smaller ones? E.g. left monitor on workspace 1, right monitor on workspace 2, and I could switch either monitor to workspace 3 if needed? Failing that, is there a way to duplicate the bottom panel onto the second monitor? Currently it is only displayed on the left one.
2013/06/26
[ "https://unix.stackexchange.com/questions/80774", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/41904/" ]
Found this on the Ubuntu Forums in a thread titled: [gnome panels on two monitors](http://ubuntuforums.org/showthread.php?t=1417900). *excerpt* I believe what you want is the following: 1. You have to right click the panels on Monitor #1 and choose "New Panel" 2. Then hold Alt and click and drag the new panel to Monitor #2. **NOTE:** "Expanded" Panels always "cling" to the edges of your physical screens and hence are unable to span across 2 monitors, this is by design. I believe all of the dual head screenshots that appear to have 2 panels stretched across are just clever layouts of 4 separate panels. ### Issue with MATE? I also came across this ticket in the Linux Mint issue tracker, which to summarize is saying that currently in MATE this feature isn't available. * [Taskbar on second monitor](https://github.com/linuxmint/Cinnamon/issues/130) ### References * [Create new panel on second monitor](http://scott.cm/create-new-panel-on-second-monitor/) * [Adding the panel to the second monitor](https://unix.stackexchange.com/questions/56523/adding-the-panel-to-the-second-monitor)
The simplest solution is to use Docky on second screen, Docky by default calls apps on screen it is on :)
80,774
I recently switched to a new PC at work, one with two (identical, Dell 23") monitors. I'm running Linux Mint 15 64bit / Cinnamon. Is there a way to set it up in such a way that, instead of both monitors sharing the same huge workspace, they are on separate smaller ones? E.g. left monitor on workspace 1, right monitor on workspace 2, and I could switch either monitor to workspace 3 if needed? Failing that, is there a way to duplicate the bottom panel onto the second monitor? Currently it is only displayed on the left one.
2013/06/26
[ "https://unix.stackexchange.com/questions/80774", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/41904/" ]
Short answer: yes, you can do this. I have my (Fedora) desktop set up this way, each monitor is an independent display. It is the same 'desktop', in the X sense, but there are some limitations to typical desktop functionality with this setup versus the 'single desktop spread over two monitors' configuration. [For example, you can't drag a window from one monitor to the other, or even drag a file from a folder on one monitor and drop it in a folder displayed on the other monitor.] Still, I prefer independent displays. For me it is natural to cycle workspaces on one monitor independently of the workspace displayed on the other monitor. I will warn you - some people are pretty zealous about which way is the 'correct way', so prepare to wade through a lot of noise and ranting if you research how to do what you want to do. I have had many people dismiss my efforts to achieve this setup because they felt it was pointless and "no sane person would want things to work that way". As another user has pointed out, some desktop environments support independent displays and others do not. I was happily using Gnome as my desktop, for ten years or more, until the 3.0 series of Gnome (which lost the capability to support independent X displays on a single desktop ... and it appears that the Gnome development community do not have an interest in resurrecting this capability). Earlier versions of Cinnamon Desktop had this capability, but with Fedora 19 or 20 I can longer achieve it with Cinnamon. I am stuck with Xfce at the moment. In order to achieve independent X displays, I had to carefully craft an xorg.conf file. For my hardware, using the proprietary nvidia driver, the key seems to be to identify multiple Devices using the same BusID, but to then use the 'metamodes' option for each Screen section to uniquely identify the port associated with each monitor in your setup. Here is my xorg.conf: ``` Section "ServerLayout" Identifier "Layout0" Screen 0 "Screen0" 0 0 Screen 1 "Screen1" RightOf "Screen0" InputDevice "Keyboard0" "CoreKeyboard" InputDevice "Mouse0" "CorePointer" Option "Xinerama" "0" EndSection Section "Files" FontPath "/usr/share/fonts/default/Type1" EndSection Section "InputDevice" # generated from default Identifier "Mouse0" Driver "mouse" Option "Protocol" "auto" Option "Device" "/dev/input/mice" Option "Emulate3Buttons" "no" Option "ZAxisMapping" "4 5" EndSection Section "InputDevice" # generated from default Identifier "Keyboard0" Driver "kbd" EndSection Section "Monitor" Identifier "Monitor0" VendorName "DELL" ModelName "P2411Hb" HorizSync 28.0 - 33.0 VertRefresh 43.0 - 72.0 Option "DPMS" EndSection Section "Device" Identifier "Device0" Driver "nvidia" VendorName "NVIDIA Corporation" BoardName "Quadro K2000M" BusID "PCI:1:0:0" Screen 0 EndSection Section "Screen" Identifier "Screen0" Device "Device0" Monitor "Monitor0" Option "TwinView" "0" Option "metamodes" "DFP-0: nvidia-auto-select +0+0" DefaultDepth 24 SubSection "Display" Depth 24 EndSubSection EndSection Section "Monitor" Identifier "Monitor1" VendorName "DELL" ModelName "P2411Hb" HorizSync 28.0 - 33.0 VertRefresh 43.0 - 72.0 Option "DPMS" EndSection Section "Device" Identifier "Device1" Driver "nvidia" VendorName "NVIDIA Corporation" BoardName "Quadro K2000M" BusID "PCI:1:0:0" Screen 1 EndSection Section "Screen" Identifier "Screen1" Device "Device1" Monitor "Monitor1" Option "TwinView" "0" Option "metamodes" "DFP-2: nvidia-auto-select +0+0" DefaultDepth 24 SubSection "Display" Depth 24 EndSubSection EndSection ``` Hopefully that gets you started. I have not found a gui tool in any Desktop Environment that reliably creates an xorg.conf supporting independent displays. My advice is to start with any 'X configuration generator' tool that comes with your chosen video driver (for example, nvidia's `nvidia-xconfig`) and see if you can use my example, above, to guide your trial-and-error.
The simplest solution is to use Docky on second screen, Docky by default calls apps on screen it is on :)
42,440,070
I have this problem: The GridView I has in the view (shown below) is too long that it doesn't fit entirely in the screen, maybe because one value parameter is too long, and it doesn't follow the text down. This this a screenshot for the GridView: [![enter image description here](https://i.stack.imgur.com/HPKAh.png)](https://i.stack.imgur.com/HPKAh.png) And this the code for the GridView ``` <?php Pjax::begin(); ?> <?= GridView::widget([ 'dataProvider' => $dataProvider, 'filterModel' => $searchModel, 'columns' => [ ['class' => 'yii\grid\SerialColumn'], 'fecha', 'nombreSesion', 'objetivosPlanificacion:ntext', ['class' => 'yii\grid\ActionColumn'], ], ]); ?> <?php Pjax::end(); ?> ```
2017/02/24
[ "https://Stackoverflow.com/questions/42440070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7575968/" ]
`java` **doesn't** supports multiple inheritance. What you are doing is implementing an `interface`. **You can't extend multiple classes in `java` but you can implement multiple interfaces**. An interface is a reference type and it is similar to class. It is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface. An interface may also contain constants, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods. A class describes the attributes and behaviors of an object and an interface contains behaviors that a class implements. For more on `interface`, [click here](https://docs.oracle.com/javase/tutorial/java/concepts/interface.html)
Java doesn't support multiple inheritance. What you have currently done is implement multiple interfaces which is absolutely permittable.
22,532,019
I adapted the following code found [here](http://pythonexcels.com/automating-pivot-tables-with-python/) to create a pivot table in my existing excel sheet: ``` import win32com.client as win32 win32c = win32.constants import sys import itertools tablecount = itertools.count(1) def addpivot(wb,sourcedata,title,filters=(),columns=(), rows=(),sumvalue=(),sortfield=""): newsheet = wb.Sheets.Add() newsheet.Cells(1,1).Value = title newsheet.Cells(1,1).Font.Size = 16 tname = "PivotTable%d"%tablecount.next() pc = wb.PivotCaches().Add(SourceType=win32c.xlDatabase, SourceData=sourcedata) pt = pc.CreatePivotTable(TableDestination="%s!R4C1"%newsheet.Name, TableName=tname, DefaultVersion=win32c.xlPivotTableVersion10) for fieldlist,fieldc in ((filters,win32c.xlPageField), (columns,win32c.xlColumnField), (rows,win32c.xlRowField)): for i,val in enumerate(fieldlist): wb.ActiveSheet.PivotTables(tname).PivotFields(val).Orientation = fieldc wb.ActiveSheet.PivotTables(tname).PivotFields(val).Position = i+1 wb.ActiveSheet.PivotTables(tname).AddDataField(wb.ActiveSheet.PivotTables(tname). PivotFields(sumvalue),sumvalue,win32c.xlSum) def runexcel(): excel = win32.gencache.EnsureDispatch('Excel.Application') #excel.Visible = True try: wb = excel.Workbooks.Open('18.03.14.xls') except: print "Failed to open spreadsheet 18.03.14.xls" sys.exit(1) ws = wb.Sheets('defaulters') xldata = ws.UsedRange.Value newdata = [] for row in xldata: if len(row) == 4 and row[-1] is not None: newdata.append(list(row)) rowcnt = len(newdata) colcnt = len(newdata[0]) wsnew = wb.Sheets.Add() wsnew.Range(wsnew.Cells(1,1),wsnew.Cells(rowcnt,colcnt)).Value = newdata wsnew.Columns.AutoFit() src = "%s!R1C1:R%dC%d"%(wsnew.Name,rowcnt,colcnt) addpivot(wb,src, title="Employees by leads", filters=("Leads",), columns=(), rows=("Name",), sumvalue="Actual hours", sortfield=()) if int(float(excel.Version)) >= 12: wb.SaveAs('new18.03.14.xlsx',win32c.xlOpenXMLWorkbook) else: wb.SaveAs('new18.03.14.xls') excel.Application.Quit() if __name__ == "__main__": runexcel() ``` This line of code, `wb.ActiveSheet.PivotTables(tname).AddDataField(wb.ActiveSheet.PivotTables(tname).PivotFields(sumvalue),sumvalue,win32c.xlSum)` returns the following error: `pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Excel', u'PivotFields method of PivotTable class failed', u'xlmain11.chm', 0, -2146827284), None)`. When I remove that line, the pivot table is generated without any data fields. Is there something I'm doing wrong?
2014/03/20
[ "https://Stackoverflow.com/questions/22532019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3335936/" ]
As this is the one of the first Google hits when searching for Excel pivot tables from Python, I post my example code. This code generates a simple pivot table in Excel through a COM server, with some basic filters, columns, rows, and some number formatting applied. I hope this helps someone not to waste half a day on it (like I did...) ``` import win32com.client Excel = win32com.client.gencache.EnsureDispatch('Excel.Application') # Excel = win32com.client.Dispatch('Excel.Application') win32c = win32com.client.constants wb = Excel.Workbooks.Add() Sheet1 = wb.Worksheets("Sheet1") TestData = [['Country','Name','Gender','Sign','Amount'], ['CH','Max' ,'M','Plus',123.4567], ['CH','Max' ,'M','Minus',-23.4567], ['CH','Max' ,'M','Plus',12.2314], ['CH','Max' ,'M','Minus',-2.2314], ['CH','Sam' ,'M','Plus',453.7685], ['CH','Sam' ,'M','Minus',-53.7685], ['CH','Sara','F','Plus',777.666], ['CH','Sara','F','Minus',-77.666], ['DE','Hans','M','Plus',345.088], ['DE','Hans','M','Minus',-45.088], ['DE','Paul','M','Plus',222.455], ['DE','Paul','M','Minus',-22.455]] for i, TestDataRow in enumerate(TestData): for j, TestDataItem in enumerate(TestDataRow): Sheet1.Cells(i+2,j+4).Value = TestDataItem cl1 = Sheet1.Cells(2,4) cl2 = Sheet1.Cells(2+len(TestData)-1,4+len(TestData[0])-1) PivotSourceRange = Sheet1.Range(cl1,cl2) PivotSourceRange.Select() Sheet2 = wb.Worksheets(2) cl3=Sheet2.Cells(4,1) PivotTargetRange= Sheet2.Range(cl3,cl3) PivotTableName = 'ReportPivotTable' PivotCache = wb.PivotCaches().Create(SourceType=win32c.xlDatabase, SourceData=PivotSourceRange, Version=win32c.xlPivotTableVersion14) PivotTable = PivotCache.CreatePivotTable(TableDestination=PivotTargetRange, TableName=PivotTableName, DefaultVersion=win32c.xlPivotTableVersion14) PivotTable.PivotFields('Name').Orientation = win32c.xlRowField PivotTable.PivotFields('Name').Position = 1 PivotTable.PivotFields('Gender').Orientation = win32c.xlPageField PivotTable.PivotFields('Gender').Position = 1 PivotTable.PivotFields('Gender').CurrentPage = 'M' PivotTable.PivotFields('Country').Orientation = win32c.xlColumnField PivotTable.PivotFields('Country').Position = 1 PivotTable.PivotFields('Country').Subtotals = [False, False, False, False, False, False, False, False, False, False, False, False] PivotTable.PivotFields('Sign').Orientation = win32c.xlColumnField PivotTable.PivotFields('Sign').Position = 2 DataField = PivotTable.AddDataField(PivotTable.PivotFields('Amount')) DataField.NumberFormat = '#\'##0.00' Excel.Visible = 1 wb.SaveAs('ranges_and_offsets.xlsx') Excel.Application.Quit() ```
Found from [PivotTable.AddDataField method (Excel)](http://msdn.microsoft.com/en-us/library/office/ff823171(v=office.15).aspx) that in `expression .AddDataField(Field, Caption, Function)` only `Field` is required and the other two parameters are optional. I removed them and the code works fine!
21,646,093
So I have a many to many relationship between Users and Photos via the pivot table `user_photo`. I use `belongsToMany('Photo')` in my User model. However the trouble here is that I have a dozen columns in my Photo table most I don't need (especially during a json response). So an example would be: ``` //Grab user #987's photos: User::with('photos')->find(987); //json output: { id: 987, name: "John Appleseed", photos: { id: 5435433, date: ..., name: 'feelsgoodman.jpg', ....// other columns that I don't need } } ``` Is it possible to modify this method such that `Photos` model will only return the accepted columns (say specified by an array `['name', 'date']`)? **User.php** ``` public function photos() { return $this->belongsToMany('Photo'); } ``` Note: I only want to select specific columns when doing a `User->belongsToMany->Photo` only. When doing something like `Photo::all()`, yes I would want all the columns as normal. EDIT: I've tried [Get specific columns using "with()" function in Laravel Eloquent](https://stackoverflow.com/questions/19852927/get-specific-columns-using-with-function-in-laravel-eloquent?rq=1) but the columns are still being selected. Also <https://github.com/laravel/laravel/issues/2306>
2014/02/08
[ "https://Stackoverflow.com/questions/21646093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3189288/" ]
You can use belongsToMany with select operation using laravel relationship. ``` public function photos() { return $this->belongsToMany('Photo')->select(array('name', 'date')); } ```
Im assuming you have a column named user\_id. Then you should be able to do the following: ``` public function photos() { return $this->belongsToMany('Photo')->select(['id', 'user_id', 'date', 'name']); } ``` You have to select, the foreign key, else it will have no way of joining it.
21,646,093
So I have a many to many relationship between Users and Photos via the pivot table `user_photo`. I use `belongsToMany('Photo')` in my User model. However the trouble here is that I have a dozen columns in my Photo table most I don't need (especially during a json response). So an example would be: ``` //Grab user #987's photos: User::with('photos')->find(987); //json output: { id: 987, name: "John Appleseed", photos: { id: 5435433, date: ..., name: 'feelsgoodman.jpg', ....// other columns that I don't need } } ``` Is it possible to modify this method such that `Photos` model will only return the accepted columns (say specified by an array `['name', 'date']`)? **User.php** ``` public function photos() { return $this->belongsToMany('Photo'); } ``` Note: I only want to select specific columns when doing a `User->belongsToMany->Photo` only. When doing something like `Photo::all()`, yes I would want all the columns as normal. EDIT: I've tried [Get specific columns using "with()" function in Laravel Eloquent](https://stackoverflow.com/questions/19852927/get-specific-columns-using-with-function-in-laravel-eloquent?rq=1) but the columns are still being selected. Also <https://github.com/laravel/laravel/issues/2306>
2014/02/08
[ "https://Stackoverflow.com/questions/21646093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3189288/" ]
You can use belongsToMany with select operation using laravel relationship. ``` public function photos() { return $this->belongsToMany('Photo')->select(array('name', 'date')); } ```
Specifying the exact columns you want for the `Photos` relationship will likely end up biting you in the butt in the future, should your application's needs ever change. A better solution would be to only specify the data you want to return in **that particular instance**, i.e. the specific JSON response you're delivering. Option 1: extend/overwrite the `toArray()` Eloquent function (which is called by `toJson()`) and change the information returned by it. This will affect *every* call to these methods, though, so it may end up giving you the same problems as doing `select()` in the original query. Option 2: Create a specific method for your JSON response and call it instead of the general `toJson()`. That method could then do any data building / array modifications necessary to achieve the specific output you need. Option 3: If you're working with an API or ajax calls in general that need a specific format, consider using a library such as [League/Fractal](https://github.com/thephpleague/fractal), which is built for just such an occasion. (Phil is also working on a [book on building APIs](https://leanpub.com/build-apis-you-wont-hate), and it doesn't suck.)
51,581,398
When we are using hive, data is not displayed in perfect table format. Column name and actual data related to column differs in position if the column name is big. How to fix it?
2018/07/29
[ "https://Stackoverflow.com/questions/51581398", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10151665/" ]
You specified the condition in `WHERE` clause for the condition that you required ``` DELETE d FROM mytab d WHERE ( d.x1 = 'b' AND d.act = 0 ) OR d.x1 is null ```
In MySQL use where clause ``` DELETE FROM mytab WHERE x1 = b AND act=0 OR x1 IS NULL;; ``` Just execute this SQL and done. It will delete rows from database matching these conditions.
51,581,398
When we are using hive, data is not displayed in perfect table format. Column name and actual data related to column differs in position if the column name is big. How to fix it?
2018/07/29
[ "https://Stackoverflow.com/questions/51581398", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10151665/" ]
You specified the condition in `WHERE` clause for the condition that you required ``` DELETE d FROM mytab d WHERE ( d.x1 = 'b' AND d.act = 0 ) OR d.x1 is null ```
For deleting rows,use `Delete` statement instead of `select` and the table name and then `where` clause for putting condition ``` Detele t1 from mytab t1 where ( x1=b and act=0 ) OR x1 IS NULL ``` here t1 is alias of table mytab
15,346,793
Hello :) How do i find out which "count"-id the loaded picture has? The loaded picture is: "df5ddc27f7569f83e3867bec71a2cac0.jpg" And my json are: ``` [ {"count":1,"file":"8b6c5592f0378dc8c56e591a7b147826.jpg"}, {"count":2,"file":"a44618c1afe93be486382ceb38536e02.jpg"}, {"count":3,"file":"3c692942d69fba0d16971e0685f42757.jpg"}, {"count":4,"file":"df5ddc27f7569f83e3867bec71a2cac0.jpg"} ] ``` Has anybody an idea for me?
2013/03/11
[ "https://Stackoverflow.com/questions/15346793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1936309/" ]
Yeah, this should be pretty straightforward. Assuming the two are siblings, you can even do this with CSS. **CSS APPROACH** ``` #site-logo { background-image: url(path/to/non-animated-image); } .login-button { /* Login default CSS here */ } .login-button:active ~ #site-logo { background-image: url(path/to/animated-image.gif); } ``` And then use an animated gif in the `.login-button:active ~ .site-logo` block. Otherwise, you can use jQuery or something similar **jQuery Approach** ``` .login-button.on('click', function(){ $('#site-logo').css('background-image', 'url(path/to/animated-image.gif)'); }); ```
The link you posted uses CSS3 animations / transitions and a canvas. And it uses a little too much fluf for my taste to achieve such a simple effect on that logo. This is not very efficient, and as Josh Burgess pointed out, you could easily do the same thing with a .gif image. However, I just wanted to highlight some of the things you see happening in this logo. (It uses a canvas, this might simply contain a gif image, but there's more to the logo than just that). I'll start with the basics of the circles you see, those are not images. You could use .gif images to achieve a similar effect. But in this case it's all CSS and HTML for the static part of the logo. An example of the circles ------------------------- ### CSS: ``` .myCircles li, .myCircles li:after { position: absolute; top: 25px; left: 25px; list-style: none;/* hide the list style */ text-indent: -9001em;/* hide the text content */ width: 50px; height: 50px; border-radius: 100% 100% 100% 100%; border-top: 5px solid #000; border-right: 5px solid #000; border-bottom: 5px solid #000; border-left: 5px solid transparent; transform: rotate(45deg); /* The transition effect */ transition: all 2s; -moz-transition: all 2s; /* Firefox 4 */ -webkit-transition: all 2s; /* Safari and Chrome */ -o-transition: all 2s; /* Opera */ } .myCircles li:after { content: ''; /* important to add this, without a content propperty set :before / :after psuedo elements will not show */ left: 25px; } .myCircles li:hover { transform: rotate(190deg); opacity: 0.5; } ``` ### HTML: ``` <ul class="myCircles"> <li id="circle"> circle </li> </ul> ``` On the website, the multiple circles are created with the :before, and :after selectors. As shown in the example above. When the animation start after clicking the button on the website, it will fade in a canvas containing that animation. For the sake of demonstration; you can add a simple :hover to see this fading effect. (fading out instead of fading in in this example.) You could use these transitions and animations on certain other events than just a :hover (or :focus :active etc), but you will need JS to do so. For example an onclick or a load event. ### HTML/JS (jQuery): ``` <button id="test">login</button> <script> $(document).ready(function(){ $('#test').click(function() { $('#circle').css( 'left', '100px' ); $('#circle').css( 'opacity', '0.5' ); }); }); </script> ``` These are the basics to the effect you see in the logo. However, I wouldn't recommend going trough the trouble of using the canvas in between there. But when using the canvas you have more freedom in the content you render, so for complex animations a canvas can come in handy. When using a canvas, you should prepare to create a lot of animations manually, or search for libraries to make use of the real power of a canvas element. As for links regarding animations and the effects you wanted to know more about: (Since this is my first post on SO it seems i can only provide you with 2 links, I'd advise you to look into css transforms and key frame animation syntax as well on CSS tricks to learn more about the possibilities of animations) CSS transforms, transitions, animations: ---------------------------------------- [CSS Transformations](http://css-tricks.com/almanac/properties/t/transition/) Canvas: ------- [Canvas animations](https://developer.mozilla.org/en-US/docs/HTML/Canvas/Tutorial/Basic_animations?redirectlocale=en-US&redirectslug=Canvas_tutorial/Basic_animations)
3,442,781
I was using one of my favorite R packages today to read data from a google spreadsheet. It would not work. This problem is occurring on all my machines (I use windows) and it appears to be a new problem. I am using Version: 0.4-1 of RGoogleDocs ``` library(RGoogleDocs) ps <-readline(prompt="get the password in ") sheets.con = getGoogleDocsConnection(getGoogleAuth("[email protected]", ps, service ="wise")) ts2=getWorksheets("OnCall",sheets.con) ``` And this is what I get after running the last line. > > Error in curlPerform(curl = curl, .opts = opts, .encoding = .encoding) : > SSL certificate problem, verify that the CA cert is OK. Details: > error:14090086:SSL routines:SSL3\_GET\_SERVER\_CERTIFICATE:certificate verify failed > > > I did some reading and came across some interesting, but not useful to me at least, information. [When I try to interact with a URL via https, I get an error of the form](http://www.omegahat.org/RCurl/FAQ.html) [Curl: SSL certificate problem, verify that the CA cert is OK](http://ademar.name/blog/2006/04/curl-ssl-certificate-problem-v.html) I got the very big picture message but did not know how to implement the solution in my script. I dropped the following line before getWorksheets. ``` x = getURLContent("https://www.google.com", ssl.verifypeer = FALSE) ``` That did not work so I tried ``` ts2=getWorksheets("OnCall",sheets.con,ssl.verifypeer = FALSE) ``` That also did not work. Interestingly enough, the following line works ``` getDocs(sheets.con,folders = FALSE) ``` What do you suggest I try to get it working again? Thanks.
2010/08/09
[ "https://Stackoverflow.com/questions/3442781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/168139/" ]
I no longer have this problem. I do not quite remember the timeline of exactly when I overcame the problem and cannot remember who helped me get here but here is a typical session which works. ``` library(RGoogleDocs) if(exists("ps")) print("got password, keep going") else ps <-readline(prompt="get the password in ") #conditional password asking options(RCurlOptions = list(capath = system.file("CurlSSL", "cacert.pem", package = "RCurl"), ssl.verifypeer = FALSE)) sheets.con = getGoogleDocsConnection(getGoogleAuth("[email protected]", ps, service ="wise")) #WARNING: this would prevent curl from detecting a 'man in the middle' attack ts2=getWorksheets("name of workbook here",sheets.con) names(ts2) sheet.1 <-sheetAsMatrix(ts2$"Sheet 1",header=TRUE, as.data.frame=TRUE, trim=TRUE) #Get one sheet other <-sheetAsMatrix(ts2$"whatever name of tab",header=TRUE, as.data.frame=TRUE, trim=TRUE) #Get other sheet ``` Does it help you?
Maybe you don't have the [certificate bundle](http://trac.macports.org/browser/trunk/dports/net/curl-ca-bundle/Portfile) installed. I installed those on OS X. You can also find them on the [curl](http://curl.haxx.se/docs/caextract.html) site
46,415,325
Microsoft has some [decent documentation](https://learn.microsoft.com/en-us/microsoft-edge/extensions/guides/debugging-extensions#content-script-debugging) on debugging Content Scripts for an Edge Extension and the top of the page even includes a [Channel 9 video](https://channel9.msdn.com/Blogs/One-Dev-Minute/Debugging-Microsoft-Edge-Extensions) on the subject. Unfortunately, the techniques [no longer seem to work](https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/13829248/), as even when following the debug instructions and using the the [sample Text Swap extension](https://github.com/MicrosoftEdge/MicrosoftEdge-Extensions-Demos), the extension and content script never show up in the debugger. [![Screenshot of Edge running Text Swap extension](https://i.stack.imgur.com/F1ShJ.png)](https://i.stack.imgur.com/F1ShJ.png) As you can see from the screenshot, the content script has run (and changed the font on the page) but it and the extension itself are nowhere to be seen in the debugger. Anyone figured out how to get the content script to show up in the debugger?
2017/09/25
[ "https://Stackoverflow.com/questions/46415325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31629/" ]
The answer is no. You only need one. NPM modules can be incorporated into your code several folders down in your project. Take for example a project folder: ``` /root app.js package.json /public index.html /node_modules ... ``` All modules in the `node-module` folder can be used in any project sub-folder. Say, you have a file named `anotherApp.js` in a folder down the line, it will 'inherit' all node modules installed in any parent folder. Therefore, it will also be able to access every module that is in the project root `node_module` folder. ``` /root /somefoldername /anotherfolder /application anotherApp.js /node_modules ... ``` I should add, that NPM (Node package manager) is there to handle locally installed modules. The `fs` (File System) modules does come with node and is installed as a global, therefore you do not need to install it via NPM. Check out <https://www.npmjs.com/> for a full list of available downloadable modules.
I would always suggest using `git` to synchronize your local files and your files on the EC2 server. To install the same dependency on both your local and cloud, you can save it in your `package.json` e.g. `npm install --save express` And on your server, `npm install` would install all the dependencies listed in `package.json`
46,415,325
Microsoft has some [decent documentation](https://learn.microsoft.com/en-us/microsoft-edge/extensions/guides/debugging-extensions#content-script-debugging) on debugging Content Scripts for an Edge Extension and the top of the page even includes a [Channel 9 video](https://channel9.msdn.com/Blogs/One-Dev-Minute/Debugging-Microsoft-Edge-Extensions) on the subject. Unfortunately, the techniques [no longer seem to work](https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/13829248/), as even when following the debug instructions and using the the [sample Text Swap extension](https://github.com/MicrosoftEdge/MicrosoftEdge-Extensions-Demos), the extension and content script never show up in the debugger. [![Screenshot of Edge running Text Swap extension](https://i.stack.imgur.com/F1ShJ.png)](https://i.stack.imgur.com/F1ShJ.png) As you can see from the screenshot, the content script has run (and changed the font on the page) but it and the extension itself are nowhere to be seen in the debugger. Anyone figured out how to get the content script to show up in the debugger?
2017/09/25
[ "https://Stackoverflow.com/questions/46415325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31629/" ]
The answer is no. You only need one. NPM modules can be incorporated into your code several folders down in your project. Take for example a project folder: ``` /root app.js package.json /public index.html /node_modules ... ``` All modules in the `node-module` folder can be used in any project sub-folder. Say, you have a file named `anotherApp.js` in a folder down the line, it will 'inherit' all node modules installed in any parent folder. Therefore, it will also be able to access every module that is in the project root `node_module` folder. ``` /root /somefoldername /anotherfolder /application anotherApp.js /node_modules ... ``` I should add, that NPM (Node package manager) is there to handle locally installed modules. The `fs` (File System) modules does come with node and is installed as a global, therefore you do not need to install it via NPM. Check out <https://www.npmjs.com/> for a full list of available downloadable modules.
You just need to insert the dependencies in your current project in your `package.json` and make sure that you create a deployment flow that installs it. If you are having trouble to deploy to your EC2 Instance, I would recommend you to start one instance using Amazon EB and use CodeShip to deploy it. Another option would be to run it using Heroku and integrating with git. Both will take care of installing the dependencies before of running it.
11,200,518
newbie here, so thanks in advance for help! I have a Wordpress site with multiple taxonomies. I'd like to create a very simple form with two select boxes, one for each taxonomy. Then I'd like to use an HTML form with the get method to display posts matching the criteria they requested from the select boxes. I'm able to do this easy enough if each of the two select boxes are filled out, I get a permalink something like: ``` testsite.com/?tax1=value1&tax2=value2 ``` (ugly, I know, but it works). What I can't figure out is what to do if they don't fill out both select boxes. Ideally it would only give the permalink for the one they fill in, so either: ``` testsite.com/?tax1=value1 or testsite.com/?tax2=value2 ``` But instead I'm getting ``` testsite.com/?tax1=value1&tax2=Select+tax ``` here is my HTML ``` <form action="http://www.testsite.com/" method="get"> Season: <select name="season"> <option>Select season</option> <option value="">Select season</option> <option value="spring">Spring</option> <option value="summer">Summer</option> <option value="fall">Fall</option> </select><br/> Vacation type: <select name="vacations"> <option value="">Select vacation type</option> <option value="beach">Beach</option> <option value="ski">Ski</option> </select><br/> <input type="submit" /> </form> ``` I realize the answer is probably simple but I'm banging my head against a wall so any help is very very much appreciated. Thank you!
2012/06/26
[ "https://Stackoverflow.com/questions/11200518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1481578/" ]
**How to get the error EAGAIN?** To get the error EAGAIN, you need to be using Non-Blocking Sockets. With Non-Blocking sockets, you need to write huge amounts of data (and stop receiving data on the peer side), so that your internal TCP buffer gets filled and returns this error. **How to get the error EPIPE?** To get the error EPIPE, you need to send large amount of data after closing the socket on the peer side. You can get more info about EPIPE error from this SO [Link](https://stackoverflow.com/questions/4584904/what-causes-the-broken-pipe-error). I had asked a question about Broken Pipe Error in the link provided and the accepted answer gives a detailed explanation. It is important to note that to get EPIPE error you should have set the flags parameter of send to MSG\_NOSIGNAL. Without that, an abnormal send can generate SIGPIPE signal. **Additional Note** Please note that it is difficult to simulate a write failure, as TCP generally stores the data that you are trying to write into it's internal buffer. So, if the internal buffer has sufficient space, then you won't get an error immediately. The best way is to try to write huge amounts of data. You can also try setting a smaller buffer size for send by using [setsockopt](http://www.manpagez.com/man/2/setsockopt/) function with SO\_SNDBUF option
You could set the receive buffer size to be really small on one side, and send a large buffer on the other. Or on the one side set the send buffer small and try to send a large message. Otherwise the most common test (I think) is to let the server and client talk for a while, and then remove a network cable.
11,200,518
newbie here, so thanks in advance for help! I have a Wordpress site with multiple taxonomies. I'd like to create a very simple form with two select boxes, one for each taxonomy. Then I'd like to use an HTML form with the get method to display posts matching the criteria they requested from the select boxes. I'm able to do this easy enough if each of the two select boxes are filled out, I get a permalink something like: ``` testsite.com/?tax1=value1&tax2=value2 ``` (ugly, I know, but it works). What I can't figure out is what to do if they don't fill out both select boxes. Ideally it would only give the permalink for the one they fill in, so either: ``` testsite.com/?tax1=value1 or testsite.com/?tax2=value2 ``` But instead I'm getting ``` testsite.com/?tax1=value1&tax2=Select+tax ``` here is my HTML ``` <form action="http://www.testsite.com/" method="get"> Season: <select name="season"> <option>Select season</option> <option value="">Select season</option> <option value="spring">Spring</option> <option value="summer">Summer</option> <option value="fall">Fall</option> </select><br/> Vacation type: <select name="vacations"> <option value="">Select vacation type</option> <option value="beach">Beach</option> <option value="ski">Ski</option> </select><br/> <input type="submit" /> </form> ``` I realize the answer is probably simple but I'm banging my head against a wall so any help is very very much appreciated. Thank you!
2012/06/26
[ "https://Stackoverflow.com/questions/11200518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1481578/" ]
You can simulate errors using [fault injection](http://en.wikipedia.org/wiki/Fault_injection). For example, [libfiu](http://blitiri.com.ar/p/libfiu/) is a fault injection library that comes with an example project that allows you to simulate errors from POSIX functions. Basically it uses `LD_PRELOAD` to inject a wrapper around the regular system calls (including `write`), and then the wrapper can be configured to either pass through to the real system call, or return whatever error you like.
You could set the receive buffer size to be really small on one side, and send a large buffer on the other. Or on the one side set the send buffer small and try to send a large message. Otherwise the most common test (I think) is to let the server and client talk for a while, and then remove a network cable.
11,200,518
newbie here, so thanks in advance for help! I have a Wordpress site with multiple taxonomies. I'd like to create a very simple form with two select boxes, one for each taxonomy. Then I'd like to use an HTML form with the get method to display posts matching the criteria they requested from the select boxes. I'm able to do this easy enough if each of the two select boxes are filled out, I get a permalink something like: ``` testsite.com/?tax1=value1&tax2=value2 ``` (ugly, I know, but it works). What I can't figure out is what to do if they don't fill out both select boxes. Ideally it would only give the permalink for the one they fill in, so either: ``` testsite.com/?tax1=value1 or testsite.com/?tax2=value2 ``` But instead I'm getting ``` testsite.com/?tax1=value1&tax2=Select+tax ``` here is my HTML ``` <form action="http://www.testsite.com/" method="get"> Season: <select name="season"> <option>Select season</option> <option value="">Select season</option> <option value="spring">Spring</option> <option value="summer">Summer</option> <option value="fall">Fall</option> </select><br/> Vacation type: <select name="vacations"> <option value="">Select vacation type</option> <option value="beach">Beach</option> <option value="ski">Ski</option> </select><br/> <input type="submit" /> </form> ``` I realize the answer is probably simple but I'm banging my head against a wall so any help is very very much appreciated. Thank you!
2012/06/26
[ "https://Stackoverflow.com/questions/11200518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1481578/" ]
**How to get the error EAGAIN?** To get the error EAGAIN, you need to be using Non-Blocking Sockets. With Non-Blocking sockets, you need to write huge amounts of data (and stop receiving data on the peer side), so that your internal TCP buffer gets filled and returns this error. **How to get the error EPIPE?** To get the error EPIPE, you need to send large amount of data after closing the socket on the peer side. You can get more info about EPIPE error from this SO [Link](https://stackoverflow.com/questions/4584904/what-causes-the-broken-pipe-error). I had asked a question about Broken Pipe Error in the link provided and the accepted answer gives a detailed explanation. It is important to note that to get EPIPE error you should have set the flags parameter of send to MSG\_NOSIGNAL. Without that, an abnormal send can generate SIGPIPE signal. **Additional Note** Please note that it is difficult to simulate a write failure, as TCP generally stores the data that you are trying to write into it's internal buffer. So, if the internal buffer has sufficient space, then you won't get an error immediately. The best way is to try to write huge amounts of data. You can also try setting a smaller buffer size for send by using [setsockopt](http://www.manpagez.com/man/2/setsockopt/) function with SO\_SNDBUF option
You can simulate errors using [fault injection](http://en.wikipedia.org/wiki/Fault_injection). For example, [libfiu](http://blitiri.com.ar/p/libfiu/) is a fault injection library that comes with an example project that allows you to simulate errors from POSIX functions. Basically it uses `LD_PRELOAD` to inject a wrapper around the regular system calls (including `write`), and then the wrapper can be configured to either pass through to the real system call, or return whatever error you like.
40,006
I'm trying to chart out a song, just so I have a chord chart to use for comping. It's in 4/4, and most chord changes happen on the strong beats (1 and 3), but there's a couple of places where beat 3 is anticipated (by an 8th note). For reference, the song is "Sultans of Swing" by Dire Straights. Is there any sort of convention used to notate, in this example, that the Bb in measure 16 should be anticipated, rather than played right on beat 3? [![SultansSnip](https://i.stack.imgur.com/Ravs7.gif)](https://i.stack.imgur.com/Ravs7.gif)
2015/12/05
[ "https://music.stackexchange.com/questions/40006", "https://music.stackexchange.com", "https://music.stackexchange.com/users/3404/" ]
(I don't have enough reputation points yet to comment, so I'll make this an answer instead. Will convert to comments on other answers later, or to edits on other answers, once I have enough cred to ask those answers' authors whether they welcome the edit.) I don't see any convention specified in either the "Concise Dictionary of Music" (Wm Collins Sons) or the "Essential Dictionary of Music Notation" (Alfred). Seems like you're on your own to come up with an approach that works best for you. As pointed out in the answer from @Tim, if you're already using staves, then why not jot out just those notes that are pushed, tying them to the downbeat chords to which they push? Or if you want to go with chord notation, maybe just use that same "Ant." abbreviation that you saw in the examples given at <http://www.musicarrangerspage.com/1493/how-to-use-anticipation-in-music/>, not as markings on written-out notes in the staff as they do there, but as stand-alone markings prior to the anticipated chord, e.g. > > Bb     Bb     Dmi     ant. Bb > > >
Since you're using a stave (don't know why), you can write in the last quaver of the bar previous to the chord to be pushed, with a tie mark across the barline. Write the actual chord over that quaver, thus before the bar. Shortly after that part, there's a syncopated Bb to C part, which really needs writing out in dots, as that rhythm pattern is crucial to the piece. Use notes as suggested by jjmusicnotes to show exactly how it's played. It's the only way.
55,012,413
New to javascript and just trying to make a simple form validation where if the user/pass is valid the box border turns green, and if invalid, it turns red (pictured) [Valid/Invalid](https://i.stack.imgur.com/Qlmd0.png) Here is my HTML: (Form Works, I'm guessing I'm screwing up on the listeners and Handlers) ``` <!DOCTYPE html> <html> <body> <form action="/action_page.php"> <input type="text" name="username" value="Username" minLength="6" maxlength="10" required> <br><br> <input type="text" name="password" value="Password" minLength="8" maxlength="15" required> <br><br> <input type="submit" value="Submit" onclick="function(changeStyle)"> </form> <script src="Script1.js"> </script> </body> </html> ``` Javascript: ``` function valid() { var textElements = document.getElementsByTagName('input'); textElements[i].addEventListener('input', function(changeStyle) { if (event.target.validity.valid) { textElements[i].style.border = "solid green 2px"; textElements[i].style.boxShadow = "0 0 5px green"; } else { textElements[i].style.border = "solid red 2px"; textElements[i].style.boxShadow = "0 0 5px red"; } }, false); } </script> ```
2019/03/05
[ "https://Stackoverflow.com/questions/55012413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8812202/" ]
``` "code": 403, "message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup." } } ``` This means that you have exceeded your limit to serve videos from youtube. You need to create an account to be able to show more videos. If you're sure you haven't exceeded your limit/ have an account double check your developer console that the API is turned on. [Developer Console](https://console.developers.google.com/apis). What I would suggest is to add a `catch` to your call to handle errors in the future. ``` axios .get("https://www.googleapis.com/youtube/v3/search", { params: { keys: API_KEY, type: "video", part: "snippet", q: searchTerm } }) .then(response => console.log(response)); .catch(err => { console.log(err); } ```
Put your Api key in url like "<https://www.googleapis.com/youtube/v3/search?key=YOUR_API_KEY>" ``` axios.get("https://www.googleapis.com/youtube/v3/search?key=Your_Api_Key", { params: { type: "video", part: "snippet", q: searchTerm } }) .then(response => console.log(response)); ``` You will find an example as well [here](https://developers.google.com/youtube/v3/getting-started)
55,012,413
New to javascript and just trying to make a simple form validation where if the user/pass is valid the box border turns green, and if invalid, it turns red (pictured) [Valid/Invalid](https://i.stack.imgur.com/Qlmd0.png) Here is my HTML: (Form Works, I'm guessing I'm screwing up on the listeners and Handlers) ``` <!DOCTYPE html> <html> <body> <form action="/action_page.php"> <input type="text" name="username" value="Username" minLength="6" maxlength="10" required> <br><br> <input type="text" name="password" value="Password" minLength="8" maxlength="15" required> <br><br> <input type="submit" value="Submit" onclick="function(changeStyle)"> </form> <script src="Script1.js"> </script> </body> </html> ``` Javascript: ``` function valid() { var textElements = document.getElementsByTagName('input'); textElements[i].addEventListener('input', function(changeStyle) { if (event.target.validity.valid) { textElements[i].style.border = "solid green 2px"; textElements[i].style.boxShadow = "0 0 5px green"; } else { textElements[i].style.border = "solid red 2px"; textElements[i].style.boxShadow = "0 0 5px red"; } }, false); } </script> ```
2019/03/05
[ "https://Stackoverflow.com/questions/55012413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8812202/" ]
``` "code": 403, "message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup." } } ``` This means that you have exceeded your limit to serve videos from youtube. You need to create an account to be able to show more videos. If you're sure you haven't exceeded your limit/ have an account double check your developer console that the API is turned on. [Developer Console](https://console.developers.google.com/apis). What I would suggest is to add a `catch` to your call to handle errors in the future. ``` axios .get("https://www.googleapis.com/youtube/v3/search", { params: { keys: API_KEY, type: "video", part: "snippet", q: searchTerm } }) .then(response => console.log(response)); .catch(err => { console.log(err); } ```
Solved this by configure/updating/enabling the settings. The api key worked in the past for me. When returning to use it again, i received a 403 error. The server understood my request, but denied me access to the info. Just go into developers console, go to enable apis, search youtube, and enable it, your key will now work as expected. [![enter image description here](https://i.stack.imgur.com/RQrDS.png)](https://i.stack.imgur.com/RQrDS.png)
55,012,413
New to javascript and just trying to make a simple form validation where if the user/pass is valid the box border turns green, and if invalid, it turns red (pictured) [Valid/Invalid](https://i.stack.imgur.com/Qlmd0.png) Here is my HTML: (Form Works, I'm guessing I'm screwing up on the listeners and Handlers) ``` <!DOCTYPE html> <html> <body> <form action="/action_page.php"> <input type="text" name="username" value="Username" minLength="6" maxlength="10" required> <br><br> <input type="text" name="password" value="Password" minLength="8" maxlength="15" required> <br><br> <input type="submit" value="Submit" onclick="function(changeStyle)"> </form> <script src="Script1.js"> </script> </body> </html> ``` Javascript: ``` function valid() { var textElements = document.getElementsByTagName('input'); textElements[i].addEventListener('input', function(changeStyle) { if (event.target.validity.valid) { textElements[i].style.border = "solid green 2px"; textElements[i].style.boxShadow = "0 0 5px green"; } else { textElements[i].style.border = "solid red 2px"; textElements[i].style.boxShadow = "0 0 5px red"; } }, false); } </script> ```
2019/03/05
[ "https://Stackoverflow.com/questions/55012413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8812202/" ]
``` "code": 403, "message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup." } } ``` This means that you have exceeded your limit to serve videos from youtube. You need to create an account to be able to show more videos. If you're sure you haven't exceeded your limit/ have an account double check your developer console that the API is turned on. [Developer Console](https://console.developers.google.com/apis). What I would suggest is to add a `catch` to your call to handle errors in the future. ``` axios .get("https://www.googleapis.com/youtube/v3/search", { params: { keys: API_KEY, type: "video", part: "snippet", q: searchTerm } }) .then(response => console.log(response)); .catch(err => { console.log(err); } ```
for some users, this error might be because of cause sanctions. so try to run your project using a DNS or VPN.
55,012,413
New to javascript and just trying to make a simple form validation where if the user/pass is valid the box border turns green, and if invalid, it turns red (pictured) [Valid/Invalid](https://i.stack.imgur.com/Qlmd0.png) Here is my HTML: (Form Works, I'm guessing I'm screwing up on the listeners and Handlers) ``` <!DOCTYPE html> <html> <body> <form action="/action_page.php"> <input type="text" name="username" value="Username" minLength="6" maxlength="10" required> <br><br> <input type="text" name="password" value="Password" minLength="8" maxlength="15" required> <br><br> <input type="submit" value="Submit" onclick="function(changeStyle)"> </form> <script src="Script1.js"> </script> </body> </html> ``` Javascript: ``` function valid() { var textElements = document.getElementsByTagName('input'); textElements[i].addEventListener('input', function(changeStyle) { if (event.target.validity.valid) { textElements[i].style.border = "solid green 2px"; textElements[i].style.boxShadow = "0 0 5px green"; } else { textElements[i].style.border = "solid red 2px"; textElements[i].style.boxShadow = "0 0 5px red"; } }, false); } </script> ```
2019/03/05
[ "https://Stackoverflow.com/questions/55012413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8812202/" ]
Put your Api key in url like "<https://www.googleapis.com/youtube/v3/search?key=YOUR_API_KEY>" ``` axios.get("https://www.googleapis.com/youtube/v3/search?key=Your_Api_Key", { params: { type: "video", part: "snippet", q: searchTerm } }) .then(response => console.log(response)); ``` You will find an example as well [here](https://developers.google.com/youtube/v3/getting-started)
Solved this by configure/updating/enabling the settings. The api key worked in the past for me. When returning to use it again, i received a 403 error. The server understood my request, but denied me access to the info. Just go into developers console, go to enable apis, search youtube, and enable it, your key will now work as expected. [![enter image description here](https://i.stack.imgur.com/RQrDS.png)](https://i.stack.imgur.com/RQrDS.png)
55,012,413
New to javascript and just trying to make a simple form validation where if the user/pass is valid the box border turns green, and if invalid, it turns red (pictured) [Valid/Invalid](https://i.stack.imgur.com/Qlmd0.png) Here is my HTML: (Form Works, I'm guessing I'm screwing up on the listeners and Handlers) ``` <!DOCTYPE html> <html> <body> <form action="/action_page.php"> <input type="text" name="username" value="Username" minLength="6" maxlength="10" required> <br><br> <input type="text" name="password" value="Password" minLength="8" maxlength="15" required> <br><br> <input type="submit" value="Submit" onclick="function(changeStyle)"> </form> <script src="Script1.js"> </script> </body> </html> ``` Javascript: ``` function valid() { var textElements = document.getElementsByTagName('input'); textElements[i].addEventListener('input', function(changeStyle) { if (event.target.validity.valid) { textElements[i].style.border = "solid green 2px"; textElements[i].style.boxShadow = "0 0 5px green"; } else { textElements[i].style.border = "solid red 2px"; textElements[i].style.boxShadow = "0 0 5px red"; } }, false); } </script> ```
2019/03/05
[ "https://Stackoverflow.com/questions/55012413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8812202/" ]
Put your Api key in url like "<https://www.googleapis.com/youtube/v3/search?key=YOUR_API_KEY>" ``` axios.get("https://www.googleapis.com/youtube/v3/search?key=Your_Api_Key", { params: { type: "video", part: "snippet", q: searchTerm } }) .then(response => console.log(response)); ``` You will find an example as well [here](https://developers.google.com/youtube/v3/getting-started)
for some users, this error might be because of cause sanctions. so try to run your project using a DNS or VPN.
69,147,252
``` <img src="https://res.cloudinary.com/dvhhqcxre/image/upload/v1611495185/zenith/tldyffcvvfm9fj51pvjp.jpg"> ``` I want to get rid of the img tag, I just want only the image link
2021/09/11
[ "https://Stackoverflow.com/questions/69147252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13574659/" ]
```js const image = document.querySelector('img') image.outerHTML = image.src ``` ```html <img src="https://res.cloudinary.com/dvhhqcxre/image/upload/v1611495185/zenith/tldyffcvvfm9fj51pvjp.jpg"> ```
You can use a [`DOMParser`](https://developer.mozilla.org/en-US/docs/Web/API/DOMParser) to parse the string and get the `src` property of the image: ```js const str = `<img src="https://res.cloudinary.com/dvhhqcxre/image/upload/v1611495185/zenith/tldyffcvvfm9fj51pvjp.jpg">`; const res = new DOMParser().parseFromString(str, "text/html").querySelector('img').src; console.log(res) ```
8,162,278
**I am getting following errors while deploying GAE application. What will be the reason for that? Stack backtrace below.** ``` Uncaught exception from servlet com.google.apphosting.runtime.HardDeadlineExceededError: This request (0000000000000000) started at 2011/11/17 04:12:01.160 UTC and was still executing at 2011/11/17 04:13:01.204 UTC. at com.google.appengine.runtime.Request.process-0000000000000000(Request.java) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:634) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) at java.net.URLClassLoader.defineClass(URLClassLoader.java:277) at sun.reflect.GeneratedMethodAccessor5.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:616) at java.lang.ClassLoader.loadClass(ClassLoader.java:266) at org.springframework.expression.spel.standard.SpelExpressionParser.doParseExpression(SpelExpressionParser.java:56) at org.springframework.expression.spel.standard.SpelExpressionParser.doParseExpression(SpelExpressionParser.java:1) at org.springframework.expression.common.TemplateAwareExpressionParser.parseExpression(TemplateAwareExpressionParser.java:66) at org.springframework.expression.common.TemplateAwareExpressionParser.parseExpression(TemplateAwareExpressionParser.java:56) at org.springframework.security.web.access.expression.ExpressionBasedFilterInvocationSecurityMetadataSource.processMap(ExpressionBasedFilterInvocationSecurityMetadataSource.java:47) at org.springframework.security.web.access.expression.ExpressionBasedFilterInvocationSecurityMetadataSource.<init>(ExpressionBasedFilterInvocationSecurityMetadataSource.java:29) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:33) at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:126) at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:108) at org.springframework.beans.factory.support.ConstructorResolver$1.run(ConstructorResolver.java:274) at java.security.AccessController.doPrivileged(Native Method) at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:272) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1003) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:907) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456) at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:270) at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:125) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1325) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1086) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425) at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47) at org.mortbay.jetty.handler.ContextHandler.startContext(ContextHandler.java:548) at org.mortbay.jetty.servlet.Context.startContext(Context.java:136) at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1250) at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:517) at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:467) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50) at com.google.tracing.TraceContext$TraceContextRunnable.runInContext(TraceContext.java:449) at com.google.tracing.TraceContext$TraceContextRunnable$1.run(TraceContext.java:455) at com.google.tracing.TraceContext.runInContext(TraceContext.java:695) at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContextNoUnref(TraceContext.java:333) at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContext(TraceContext.java:325) at com.google.tracing.TraceContext$TraceContextRunnable.run(TraceContext.java:453) at java.lang.Thread.run(Thread.java:679) ``` with following explanation: This request caused a new process to be started for your application, and thus caused your application code to be loaded for the first time. This request may thus take longer and use more CPU than a typical request for your application. A serious problem was encountered with the process that handled this request, causing it to exit. This is likely to cause a new process to be used for the next request to your application. If you see this message frequently, you may be throwing exceptions during the initialization of your application. (Error code 104)
2011/11/17
[ "https://Stackoverflow.com/questions/8162278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/930544/" ]
As it says in the stacktrace: ``` HardDeadlineExceededError: This request (0000000000000000) started at 2011/11/17 04:12:01.160 UTC and was still executing at 2011/11/17 04:13:01.204 UTC. ``` Frontend requests to App Engine apps have 60 seconds to complete. If your request takes longer than that, it will be terminated. If you need to do a lot of work, you should do it on the Task Queue.
You need to optimize your application for quick setup. For example: * Uses a lightweight framework * Reduces classes scanning (discovery) at framework setup * Minimizes operations in ServletContextListener#contextInitialized There is a long way for GAE application optimizations, good luck ;-)
8,162,278
**I am getting following errors while deploying GAE application. What will be the reason for that? Stack backtrace below.** ``` Uncaught exception from servlet com.google.apphosting.runtime.HardDeadlineExceededError: This request (0000000000000000) started at 2011/11/17 04:12:01.160 UTC and was still executing at 2011/11/17 04:13:01.204 UTC. at com.google.appengine.runtime.Request.process-0000000000000000(Request.java) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:634) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) at java.net.URLClassLoader.defineClass(URLClassLoader.java:277) at sun.reflect.GeneratedMethodAccessor5.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:616) at java.lang.ClassLoader.loadClass(ClassLoader.java:266) at org.springframework.expression.spel.standard.SpelExpressionParser.doParseExpression(SpelExpressionParser.java:56) at org.springframework.expression.spel.standard.SpelExpressionParser.doParseExpression(SpelExpressionParser.java:1) at org.springframework.expression.common.TemplateAwareExpressionParser.parseExpression(TemplateAwareExpressionParser.java:66) at org.springframework.expression.common.TemplateAwareExpressionParser.parseExpression(TemplateAwareExpressionParser.java:56) at org.springframework.security.web.access.expression.ExpressionBasedFilterInvocationSecurityMetadataSource.processMap(ExpressionBasedFilterInvocationSecurityMetadataSource.java:47) at org.springframework.security.web.access.expression.ExpressionBasedFilterInvocationSecurityMetadataSource.<init>(ExpressionBasedFilterInvocationSecurityMetadataSource.java:29) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:33) at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:126) at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:108) at org.springframework.beans.factory.support.ConstructorResolver$1.run(ConstructorResolver.java:274) at java.security.AccessController.doPrivileged(Native Method) at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:272) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1003) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:907) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456) at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:270) at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:125) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1325) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1086) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425) at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47) at org.mortbay.jetty.handler.ContextHandler.startContext(ContextHandler.java:548) at org.mortbay.jetty.servlet.Context.startContext(Context.java:136) at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1250) at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:517) at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:467) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50) at com.google.tracing.TraceContext$TraceContextRunnable.runInContext(TraceContext.java:449) at com.google.tracing.TraceContext$TraceContextRunnable$1.run(TraceContext.java:455) at com.google.tracing.TraceContext.runInContext(TraceContext.java:695) at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContextNoUnref(TraceContext.java:333) at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContext(TraceContext.java:325) at com.google.tracing.TraceContext$TraceContextRunnable.run(TraceContext.java:453) at java.lang.Thread.run(Thread.java:679) ``` with following explanation: This request caused a new process to be started for your application, and thus caused your application code to be loaded for the first time. This request may thus take longer and use more CPU than a typical request for your application. A serious problem was encountered with the process that handled this request, causing it to exit. This is likely to cause a new process to be used for the next request to your application. If you see this message frequently, you may be throwing exceptions during the initialization of your application. (Error code 104)
2011/11/17
[ "https://Stackoverflow.com/questions/8162278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/930544/" ]
Finally we sorted the issue by removing `<prop key="hibernate.hbm2ddl.auto">update</prop>` from the hibernate configuration,which was for automatically exporting schema DDL to the database when the SessionFactory is created.
You need to optimize your application for quick setup. For example: * Uses a lightweight framework * Reduces classes scanning (discovery) at framework setup * Minimizes operations in ServletContextListener#contextInitialized There is a long way for GAE application optimizations, good luck ;-)
53,203,011
It's abundantly clear to me that when we want to delete a node in a Linked List (be it doubly or singly linked), and we have to search for this node, the time complexity for this task is O(n), as we must traverse the whole list in the worst case to identify the node. Similarly, it is O(k) if we want to delete the k-th node, and we don't have a reference to this node already. It is commonly cited that one of the benefits of using a doubly linked list over a singly linked list is that deletion is O(1) when we have a reference to the node we want to delete. I.e., if you want to delete the Node i, simply do the following: i.prev.next = i.next and i.next.prev = i.prev It is said that deletion is O(1) in a singly linked list ONLY if you have a reference to the node prior to the one you want to delete. However, I don't think this is necessarily the case. If you want to delete Node i (and you have a reference to Node i), why can't you just copy over the data from i.next, and set i.next = i.next.next? This would also be O(1), as in the doubly linked list case, meaning that deletion is no more efficient in a doubly linked list in ANY case, as far as Big-O is concerned. Of course, this idea wouldn't work if the node you're trying to delete is the last node in the linked list. It's really bugging me that no one remembers this when comparing singly and doubly linked lists. What am I missing? **To clarify**: what I'm suggesting in the singly linked case is **overwriting the data at the Node you want to delete**, with the data from the next node, and then deleting the next node. This has the same desired effect as deleting Node `i`, though it is not what you're doing per se. **EDIT** **What I've Learned:** So it seems that I am correct to some extent. First of all, many people mentioned that my solution isn't complete, as deletion of the last element is a problem, so my algorithm is O(n) (by definition of Big-O). I naively suggested in response to get around this by keeping track of the "2nd to last node" in your list - of course, this causes problems once the last node in your list has been deleted the first time. A solution that was suggested, and does seem to work, is to demarcate the end of your list with something like a NullNode, and I like this approach. Other problems that were presented were referential integrity, and the time associated with copying the data itself from the next node (i.e. presumably, a costly deep copy might be necessary). If you can assume that you don't have other objects using the node that you're copying, and that the task of copying is O(1) in itself, then it seems like my solution works. Although, at this point, maybe its worth it to just use a Doubly Linked List :)
2018/11/08
[ "https://Stackoverflow.com/questions/53203011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10622251/" ]
It is true that copying data from `i.next` to `i` and then deleting `i` would be `O(1)` assuming that copying the data is also `O(1)`. But even with this algorithm, since deleting the last element is `O(n)`, and a description of a function in terms of big O notation only provides an upper bound on the growth rate of the function, that means your algorithm is still `O(n)`. Regarding your comment: > > I guess my dissatisfaction comes from the fact that textbooks and basically every resource online cites the #1 biggest advantage of doubly linked lists is deletion - this seems a little disingenuous. It's a very specific case of deletion - deletion at the tail! If efficient deletion is all you're going for, seems like this doesn't warrant using a doubly instead of a singly linked list (due to all the overhead necessary of having double the number of pointers). Simply store a reference to the second to last node in your list, and you're good to go! > > > You can certainly store a reference to the second to last node and make deletion of the last node `O(1)`, but this would be the case only for the first time you delete the last node. You could update the reference to the node before it, but finding it will be `O(n)`. You can solve this if you keep a reference to second to last element, and so on. At this point, you have reasoned your way to a doubly linked list, whose main advantage is deletion, and since you already have pointers to previous nodes you don't really need to move values around. **Remember that big `O` notation talks about the worst case scenario, so if even a single case is `O(n)` then your entire algorithm is `O(n)`.** When you say a solution is `O(n)` you are basically saying *"in the worst possible case, this algorithm will grow as fast as `n` grows"*. Big `O` does not talk about expected or average performance, and it's a great theoretical tool, but you need to consider your particular use cases when deciding what to use. Additionally, if you need to preserve reference integrity, you would not want to move values from one node to the other, i.e. if you tad a reference to node `i+1` and delete node `i`, you wouldn't expect your reference to be silently invalid, so when removing elements the more robust option is to delete the node itself.
> > It is said that deletion is O(1) in a singly linked list ONLY if you > have a reference to the node prior to the one you want to delete. > However, I don't think this is necessarily the case. If you want to > delete Node i (and you have a reference to Node i), why can't you just > copy over the data from i.next, and set i.next = i.next.next? > > > Because it is the previous node's "next" member that you want to set equal to what i.next points to before you delete i. Finding the previous node is an O(N) operation for single-linked list, if you don't have a reference to it. For a double-linked list, finding the previous node is a O(1) operation as it should be i.prev
53,203,011
It's abundantly clear to me that when we want to delete a node in a Linked List (be it doubly or singly linked), and we have to search for this node, the time complexity for this task is O(n), as we must traverse the whole list in the worst case to identify the node. Similarly, it is O(k) if we want to delete the k-th node, and we don't have a reference to this node already. It is commonly cited that one of the benefits of using a doubly linked list over a singly linked list is that deletion is O(1) when we have a reference to the node we want to delete. I.e., if you want to delete the Node i, simply do the following: i.prev.next = i.next and i.next.prev = i.prev It is said that deletion is O(1) in a singly linked list ONLY if you have a reference to the node prior to the one you want to delete. However, I don't think this is necessarily the case. If you want to delete Node i (and you have a reference to Node i), why can't you just copy over the data from i.next, and set i.next = i.next.next? This would also be O(1), as in the doubly linked list case, meaning that deletion is no more efficient in a doubly linked list in ANY case, as far as Big-O is concerned. Of course, this idea wouldn't work if the node you're trying to delete is the last node in the linked list. It's really bugging me that no one remembers this when comparing singly and doubly linked lists. What am I missing? **To clarify**: what I'm suggesting in the singly linked case is **overwriting the data at the Node you want to delete**, with the data from the next node, and then deleting the next node. This has the same desired effect as deleting Node `i`, though it is not what you're doing per se. **EDIT** **What I've Learned:** So it seems that I am correct to some extent. First of all, many people mentioned that my solution isn't complete, as deletion of the last element is a problem, so my algorithm is O(n) (by definition of Big-O). I naively suggested in response to get around this by keeping track of the "2nd to last node" in your list - of course, this causes problems once the last node in your list has been deleted the first time. A solution that was suggested, and does seem to work, is to demarcate the end of your list with something like a NullNode, and I like this approach. Other problems that were presented were referential integrity, and the time associated with copying the data itself from the next node (i.e. presumably, a costly deep copy might be necessary). If you can assume that you don't have other objects using the node that you're copying, and that the task of copying is O(1) in itself, then it seems like my solution works. Although, at this point, maybe its worth it to just use a Doubly Linked List :)
2018/11/08
[ "https://Stackoverflow.com/questions/53203011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10622251/" ]
For a node in the middle of the list you need to modify the *previous* node (so its "next" pointer is pointing to the removed nodes "next"). With a double-linked list it's simple since the node to delete contains a pointer to the previous node. That's not possible with s single-linked list, where you need to iterate over list until you find a node whose "next" pointer is the node to delete. Therefore removing a node in a double-linked list is O(1). And for a single-linked list it's O(n), where n is the number of nodes before the node you want to remove.
The problem with this approach is that it invalidates the wrong reference. Deleting the node shall only invalidate a reference to *that* node, while the references to *any other* node shall remain valid. As long as you do not hold any reference to the list, this approach would work. Otherwise it is prone to failure.
53,203,011
It's abundantly clear to me that when we want to delete a node in a Linked List (be it doubly or singly linked), and we have to search for this node, the time complexity for this task is O(n), as we must traverse the whole list in the worst case to identify the node. Similarly, it is O(k) if we want to delete the k-th node, and we don't have a reference to this node already. It is commonly cited that one of the benefits of using a doubly linked list over a singly linked list is that deletion is O(1) when we have a reference to the node we want to delete. I.e., if you want to delete the Node i, simply do the following: i.prev.next = i.next and i.next.prev = i.prev It is said that deletion is O(1) in a singly linked list ONLY if you have a reference to the node prior to the one you want to delete. However, I don't think this is necessarily the case. If you want to delete Node i (and you have a reference to Node i), why can't you just copy over the data from i.next, and set i.next = i.next.next? This would also be O(1), as in the doubly linked list case, meaning that deletion is no more efficient in a doubly linked list in ANY case, as far as Big-O is concerned. Of course, this idea wouldn't work if the node you're trying to delete is the last node in the linked list. It's really bugging me that no one remembers this when comparing singly and doubly linked lists. What am I missing? **To clarify**: what I'm suggesting in the singly linked case is **overwriting the data at the Node you want to delete**, with the data from the next node, and then deleting the next node. This has the same desired effect as deleting Node `i`, though it is not what you're doing per se. **EDIT** **What I've Learned:** So it seems that I am correct to some extent. First of all, many people mentioned that my solution isn't complete, as deletion of the last element is a problem, so my algorithm is O(n) (by definition of Big-O). I naively suggested in response to get around this by keeping track of the "2nd to last node" in your list - of course, this causes problems once the last node in your list has been deleted the first time. A solution that was suggested, and does seem to work, is to demarcate the end of your list with something like a NullNode, and I like this approach. Other problems that were presented were referential integrity, and the time associated with copying the data itself from the next node (i.e. presumably, a costly deep copy might be necessary). If you can assume that you don't have other objects using the node that you're copying, and that the task of copying is O(1) in itself, then it seems like my solution works. Although, at this point, maybe its worth it to just use a Doubly Linked List :)
2018/11/08
[ "https://Stackoverflow.com/questions/53203011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10622251/" ]
For a node in the middle of the list you need to modify the *previous* node (so its "next" pointer is pointing to the removed nodes "next"). With a double-linked list it's simple since the node to delete contains a pointer to the previous node. That's not possible with s single-linked list, where you need to iterate over list until you find a node whose "next" pointer is the node to delete. Therefore removing a node in a double-linked list is O(1). And for a single-linked list it's O(n), where n is the number of nodes before the node you want to remove.
Nice question. Simple answer: The alternate solution you are suggesting for singly linked lists is not complete and fails when you are given the last node for deletion. There is no way that you can make the previous to last node point to null. Hence, for a valid solution, the complexity in case of deletion in the singly linked list is O(n).
53,203,011
It's abundantly clear to me that when we want to delete a node in a Linked List (be it doubly or singly linked), and we have to search for this node, the time complexity for this task is O(n), as we must traverse the whole list in the worst case to identify the node. Similarly, it is O(k) if we want to delete the k-th node, and we don't have a reference to this node already. It is commonly cited that one of the benefits of using a doubly linked list over a singly linked list is that deletion is O(1) when we have a reference to the node we want to delete. I.e., if you want to delete the Node i, simply do the following: i.prev.next = i.next and i.next.prev = i.prev It is said that deletion is O(1) in a singly linked list ONLY if you have a reference to the node prior to the one you want to delete. However, I don't think this is necessarily the case. If you want to delete Node i (and you have a reference to Node i), why can't you just copy over the data from i.next, and set i.next = i.next.next? This would also be O(1), as in the doubly linked list case, meaning that deletion is no more efficient in a doubly linked list in ANY case, as far as Big-O is concerned. Of course, this idea wouldn't work if the node you're trying to delete is the last node in the linked list. It's really bugging me that no one remembers this when comparing singly and doubly linked lists. What am I missing? **To clarify**: what I'm suggesting in the singly linked case is **overwriting the data at the Node you want to delete**, with the data from the next node, and then deleting the next node. This has the same desired effect as deleting Node `i`, though it is not what you're doing per se. **EDIT** **What I've Learned:** So it seems that I am correct to some extent. First of all, many people mentioned that my solution isn't complete, as deletion of the last element is a problem, so my algorithm is O(n) (by definition of Big-O). I naively suggested in response to get around this by keeping track of the "2nd to last node" in your list - of course, this causes problems once the last node in your list has been deleted the first time. A solution that was suggested, and does seem to work, is to demarcate the end of your list with something like a NullNode, and I like this approach. Other problems that were presented were referential integrity, and the time associated with copying the data itself from the next node (i.e. presumably, a costly deep copy might be necessary). If you can assume that you don't have other objects using the node that you're copying, and that the task of copying is O(1) in itself, then it seems like my solution works. Although, at this point, maybe its worth it to just use a Doubly Linked List :)
2018/11/08
[ "https://Stackoverflow.com/questions/53203011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10622251/" ]
It is true that copying data from `i.next` to `i` and then deleting `i` would be `O(1)` assuming that copying the data is also `O(1)`. But even with this algorithm, since deleting the last element is `O(n)`, and a description of a function in terms of big O notation only provides an upper bound on the growth rate of the function, that means your algorithm is still `O(n)`. Regarding your comment: > > I guess my dissatisfaction comes from the fact that textbooks and basically every resource online cites the #1 biggest advantage of doubly linked lists is deletion - this seems a little disingenuous. It's a very specific case of deletion - deletion at the tail! If efficient deletion is all you're going for, seems like this doesn't warrant using a doubly instead of a singly linked list (due to all the overhead necessary of having double the number of pointers). Simply store a reference to the second to last node in your list, and you're good to go! > > > You can certainly store a reference to the second to last node and make deletion of the last node `O(1)`, but this would be the case only for the first time you delete the last node. You could update the reference to the node before it, but finding it will be `O(n)`. You can solve this if you keep a reference to second to last element, and so on. At this point, you have reasoned your way to a doubly linked list, whose main advantage is deletion, and since you already have pointers to previous nodes you don't really need to move values around. **Remember that big `O` notation talks about the worst case scenario, so if even a single case is `O(n)` then your entire algorithm is `O(n)`.** When you say a solution is `O(n)` you are basically saying *"in the worst possible case, this algorithm will grow as fast as `n` grows"*. Big `O` does not talk about expected or average performance, and it's a great theoretical tool, but you need to consider your particular use cases when deciding what to use. Additionally, if you need to preserve reference integrity, you would not want to move values from one node to the other, i.e. if you tad a reference to node `i+1` and delete node `i`, you wouldn't expect your reference to be silently invalid, so when removing elements the more robust option is to delete the node itself.
Nice question. Simple answer: The alternate solution you are suggesting for singly linked lists is not complete and fails when you are given the last node for deletion. There is no way that you can make the previous to last node point to null. Hence, for a valid solution, the complexity in case of deletion in the singly linked list is O(n).
53,203,011
It's abundantly clear to me that when we want to delete a node in a Linked List (be it doubly or singly linked), and we have to search for this node, the time complexity for this task is O(n), as we must traverse the whole list in the worst case to identify the node. Similarly, it is O(k) if we want to delete the k-th node, and we don't have a reference to this node already. It is commonly cited that one of the benefits of using a doubly linked list over a singly linked list is that deletion is O(1) when we have a reference to the node we want to delete. I.e., if you want to delete the Node i, simply do the following: i.prev.next = i.next and i.next.prev = i.prev It is said that deletion is O(1) in a singly linked list ONLY if you have a reference to the node prior to the one you want to delete. However, I don't think this is necessarily the case. If you want to delete Node i (and you have a reference to Node i), why can't you just copy over the data from i.next, and set i.next = i.next.next? This would also be O(1), as in the doubly linked list case, meaning that deletion is no more efficient in a doubly linked list in ANY case, as far as Big-O is concerned. Of course, this idea wouldn't work if the node you're trying to delete is the last node in the linked list. It's really bugging me that no one remembers this when comparing singly and doubly linked lists. What am I missing? **To clarify**: what I'm suggesting in the singly linked case is **overwriting the data at the Node you want to delete**, with the data from the next node, and then deleting the next node. This has the same desired effect as deleting Node `i`, though it is not what you're doing per se. **EDIT** **What I've Learned:** So it seems that I am correct to some extent. First of all, many people mentioned that my solution isn't complete, as deletion of the last element is a problem, so my algorithm is O(n) (by definition of Big-O). I naively suggested in response to get around this by keeping track of the "2nd to last node" in your list - of course, this causes problems once the last node in your list has been deleted the first time. A solution that was suggested, and does seem to work, is to demarcate the end of your list with something like a NullNode, and I like this approach. Other problems that were presented were referential integrity, and the time associated with copying the data itself from the next node (i.e. presumably, a costly deep copy might be necessary). If you can assume that you don't have other objects using the node that you're copying, and that the task of copying is O(1) in itself, then it seems like my solution works. Although, at this point, maybe its worth it to just use a Doubly Linked List :)
2018/11/08
[ "https://Stackoverflow.com/questions/53203011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10622251/" ]
It is true that copying data from `i.next` to `i` and then deleting `i` would be `O(1)` assuming that copying the data is also `O(1)`. But even with this algorithm, since deleting the last element is `O(n)`, and a description of a function in terms of big O notation only provides an upper bound on the growth rate of the function, that means your algorithm is still `O(n)`. Regarding your comment: > > I guess my dissatisfaction comes from the fact that textbooks and basically every resource online cites the #1 biggest advantage of doubly linked lists is deletion - this seems a little disingenuous. It's a very specific case of deletion - deletion at the tail! If efficient deletion is all you're going for, seems like this doesn't warrant using a doubly instead of a singly linked list (due to all the overhead necessary of having double the number of pointers). Simply store a reference to the second to last node in your list, and you're good to go! > > > You can certainly store a reference to the second to last node and make deletion of the last node `O(1)`, but this would be the case only for the first time you delete the last node. You could update the reference to the node before it, but finding it will be `O(n)`. You can solve this if you keep a reference to second to last element, and so on. At this point, you have reasoned your way to a doubly linked list, whose main advantage is deletion, and since you already have pointers to previous nodes you don't really need to move values around. **Remember that big `O` notation talks about the worst case scenario, so if even a single case is `O(n)` then your entire algorithm is `O(n)`.** When you say a solution is `O(n)` you are basically saying *"in the worst possible case, this algorithm will grow as fast as `n` grows"*. Big `O` does not talk about expected or average performance, and it's a great theoretical tool, but you need to consider your particular use cases when deciding what to use. Additionally, if you need to preserve reference integrity, you would not want to move values from one node to the other, i.e. if you tad a reference to node `i+1` and delete node `i`, you wouldn't expect your reference to be silently invalid, so when removing elements the more robust option is to delete the node itself.
I was looking this up as a way to explain it and get references for a blog post. Assuming you have to look up the node, like we do often with arrays and lists to find a value, you can only travel in one direction, and it will take O^n times in double and single link lists to get to the node and retrieve it's address in memory. In a double linked list, once you have the nodes location you can set the pointers for the previous and the next node as needed without having to temporarily store any data. I think your idea would work, regardless of the last node issue, if while traversing to find the node in question that needs to be removed, a temp value, for the previous node is kept track of. I think the real issue is in a single linked list you'd have to hold the node addresses in a temporary variable as you traverse to assign the new pointers. On each node, we'd have to store the current node as a previous, and the next node as the next so that pointer reassignment could be done, which is essentially what the double linked list does as it's created. Even if we have to travel to the end node, if the previous is kept in a temporary variable, we could go back to assign a none to it's next pointer. But still, this is what the doubly linked list accomplishes my storing the addresses for it's neighbors, and then nothing has to go into a temporary state for the search and deletion. Consider also that the O^n might not be the benefit, but in not having to place temporary data to do the removal. At the location of the node, we can access the neighbors in a doubly linked list, and in a single linked list, we would have to store data temporarily on each iteration for when the value is found. There's always the possibility the data would not be in the list. In a doubly linked list, the traversal would happen without having to store temporary information. What if there are parallel processes and that temporary data is changed before the pointer swap can happen? What happens if that temporary data is deleted before the new assignment? Just some thoughts on it. Was hoping for a more thorough explanation myself. Wikipedia: <https://en.wikipedia.org/wiki/Doubly_linked_list>